本文整理汇总了C#中System.IO.StreamWriter类的典型用法代码示例。如果您正苦于以下问题:C# StreamWriter类的具体用法?C# StreamWriter怎么用?C# StreamWriter使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
StreamWriter类属于System.IO命名空间,在下文中一共展示了StreamWriter类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Run
public static void Run()
{
// ExStart:ExtractTextFromPageRegion
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Text();
// Open document
Document pdfDocument = new Document(dataDir + "ExtractTextAll.pdf");
// Create TextAbsorber object to extract text
TextAbsorber absorber = new TextAbsorber();
absorber.TextSearchOptions.LimitToPageBounds = true;
absorber.TextSearchOptions.Rectangle = new Aspose.Pdf.Rectangle(100, 200, 250, 350);
// Accept the absorber for first page
pdfDocument.Pages[1].Accept(absorber);
// Get the extracted text
string extractedText = absorber.Text;
// Create a writer and open the file
TextWriter tw = new StreamWriter(dataDir + "extracted-text.txt");
// Write a line of text to the file
tw.WriteLine(extractedText);
// Close the stream
tw.Close();
// ExEnd:ExtractTextFromPageRegion
}
示例2: WriteToLog
/// <summary>
/// Запись в ЛОГ-файл
/// </summary>
/// <param name="str"></param>
public void WriteToLog(string str, bool doWrite = true)
{
if (doWrite)
{
StreamWriter sw = null;
FileStream fs = null;
try
{
string curDir = AppDomain.CurrentDomain.BaseDirectory;
fs = new FileStream(curDir + "teplouchetlog.pi", FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
sw = new StreamWriter(fs, Encoding.Default);
if (m_vport == null) sw.WriteLine(DateTime.Now.ToString() + ": Unknown port: adress: " + m_address + ": " + str);
else sw.WriteLine(DateTime.Now.ToString() + ": " + m_vport.GetName() + ": adress: " + m_address + ": " + str);
sw.Close();
fs.Close();
}
catch
{
}
finally
{
if (sw != null)
{
sw.Close();
sw = null;
}
if (fs != null)
{
fs.Close();
fs = null;
}
}
}
}
示例3: CreateLog
public void CreateLog(Exception ex)
{
try
{
using (TextWriter writer = new StreamWriter(_filename, false))
{
writer.WriteLine("Crash Log: {0}", _crashTime);
writer.WriteLine("= System Information");
writer.Write(SystemInfo());
writer.WriteLine();
writer.WriteLine("= Disk Information");
writer.Write(DriveInfo());
writer.WriteLine();
writer.WriteLine("= Exception Information");
writer.Write(ExceptionInfo(ex));
writer.WriteLine();
writer.WriteLine();
writer.WriteLine("= MediaPortal Information");
writer.WriteLine();
IList<string> statusList = ServiceRegistration.Instance.GetStatus();
foreach (string status in statusList)
writer.WriteLine(status);
}
}
catch (Exception e)
{
Console.WriteLine("UiCrashLogger crashed:");
Console.WriteLine(e.ToString());
}
}
示例4: using
void IMapExporter.Save(string filename, Dictionary<string, System.Drawing.Rectangle> map)
{
// Original filename New filename, ?, 2D, X Y, MAGIC Width Height
//.\Animations\player_fall_ne_9.png 0_Animations.png, 0, 2D, 0.000000, 0.000000, 0.000000, 0.058594, 0.064453
// copy the files list and sort alphabetically
string[] keys = new string[map.Count];
map.Keys.CopyTo(keys, 0);
List<string> outputFiles = new List<string>(keys);
outputFiles.Sort();
using (StreamWriter writer = new StreamWriter(filename))
{
foreach (var image in outputFiles)
{
// get the destination rectangle
Rectangle destination = map[image];
// write out the destination rectangle for this bitmap
//line = item.SourceName + "\t\t" + item.Destination + ", 0, 2D, " + item.ScaledRect.X.ToString("0.000000") + ", " +
//item.ScaledRect.Y.ToString("0.000000") + ", 0.000000, " + item.ScaledRect.Width.ToString("0.000000") + ", " + item.ScaledRect.Height.ToString("0.000000");
writer.WriteLine(string.Format(
"{0}\t\t{1}, 0, 2D, {2:F5}, {3:F5}, 0.00000, {4:F5}, {5:F5}",
image,
Path.GetFileNameWithoutExtension(filename)+".png",
(float)destination.X / atlasWidth,
(float)destination.Y / atlasHeight,
(float)destination.Width / atlasWidth,
(float)destination.Height / atlasHeight));
}
}
}
示例5: CheckAndChangeNewFile
private void CheckAndChangeNewFile()
{
if (this.writer.BaseStream.Length >= this.maxLength)
{
this.writer.Close();
this.writer = null;
string fileName = ESBasic.Helpers.FileHelper.GetFileNameNoPath(this.iniPath);
string dir = ESBasic.Helpers.FileHelper.GetFileDirectory(this.iniPath);
int pos = fileName.LastIndexOf('.');
string extendName = null;
string pureName = fileName;
if (pos >=0)
{
extendName = fileName.Substring(pos+1);
pureName = fileName.Substring(0, pos);
}
string newPath = null;
for(int i=1;i<1000;i++)
{
string newName = pureName + "_" + i.ToString("000");
if (extendName != null)
{
newName += "." + extendName;
}
newPath = dir + "\\" + newName;
if (!File.Exists(newPath))
{
break;
}
}
this.writer = new StreamWriter(File.Open(newPath, FileMode.OpenOrCreate | FileMode.Append, FileAccess.Write, FileShare.Read));
}
}
示例6: Extract
public static void Extract(Category category)
{
string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Data", "Extract");
if(!Directory.Exists(path))
Directory.CreateDirectory(path);
pset.Clear();
pdic.Clear();
string downPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Data", "Down", category.Name);
string fileName = string.Format(@"{0}\{1}.txt", path, category.Name);
StreamWriter sw = new StreamWriter(fileName, false, Encoding.UTF8);
for (int i = category.DownPageCount; i >= 1; i--)
{
string htmlFileName = string.Format(@"{0}\{1}.html", downPath, i);
if (!File.Exists(htmlFileName))
Logger.Instance.Write(string.Format("{0}-{1}.html-not exist", category.Name, i));
StreamReader sr = new StreamReader(htmlFileName, Encoding.UTF8);
string text = sr.ReadToEnd();
sr.Close();
var action = CreateAction(category.Type);
if (action == null) continue;
Extract(text, sw, category.Name,category.DbName, action);
}
sw.Close();
Console.WriteLine("{0}:Extract Data Finished!", category.Name);
}
示例7: EncryptString
public static string EncryptString(string plainText)
{
byte[] encrypted;
AesCryptoServiceProvider provider = createAesProvider();
// Create a decrytor to perform the stream transform.
ICryptoTransform encryptor = provider.CreateEncryptor(provider.Key, null); // null IV, because ECB mode
// Create the streams used for encryption.
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
//Write all data to the stream.
swEncrypt.Write(plainText);
}
encrypted = msEncrypt.ToArray();
}
}
// Return the encrypted bytes from the memory stream.
return encoding.GetString(encrypted);
}
示例8: SaveLastCode
private void SaveLastCode()
{
string filename = Path.Combine(localPath, "TestApp.os");
using (var writer = new StreamWriter(filename, false, Encoding.UTF8))
{
// первой строкой запишем имя открытого файла
writer.Write("//"); // знаки комментария, чтобы сохранить код правильным
writer.WriteLine(_currentDocPath);
// второй строкой - признак изменённости
writer.Write("//");
writer.WriteLine(_isModified);
args.Text = args.Text.TrimEnd('\r', '\n');
// запишем аргументы командной строки
writer.Write("//");
writer.WriteLine(args.LineCount);
for (var i = 0; i < args.LineCount; ++i )
{
string s = args.GetLineText(i).TrimEnd('\r', '\n');
writer.Write("//");
writer.WriteLine(s);
}
// и потом сам код
writer.Write(txtCode.Text);
}
}
示例9: Trace
public void Trace(NetState state)
{
try
{
string path = Path.Combine(Paths.LogsDirectory, "packets.log");
using (StreamWriter sw = new StreamWriter(path, true))
{
sw.BaseStream.Seek(sw.BaseStream.Length, SeekOrigin.Begin);
byte[] buffer = _data;
if (_data.Length > 0)
Tracer.Warn(string.Format("Unhandled packet 0x{0:X2}", _data[0]));
buffer.ToFormattedString(buffer.Length, sw);
sw.WriteLine();
sw.WriteLine();
}
}
catch (Exception e)
{
Tracer.Error(e);
}
}
示例10: Write
protected override async void Write(Core.LogEventInfo logEvent)
{
var request = (HttpWebRequest) WebRequest.Create(ServerUrl);
request.ContentType = "application/json; charset=utf-8";
request.Method = "POST";
var requestWriter = new StreamWriter(request.GetRequestStream());
requestWriter.Write("{ "
+ "\"version\": " + "\"" + "1.0" + "\",\n"
+ "\"host\": " + "\"" + AndroidId + "\",\n"
+ "\"short_message\": " + "\"" + logEvent.FormattedMessage + "\",\n"
+ "\"full_message\": " + "\"" + logEvent.FormattedMessage + "\",\n"
+ "\"timestamp\": " + "\"" + DateTime.Now.ToString(CultureInfo.InvariantCulture) +
"\",\n"
+ "\"level\": " + "\"" +
logEvent.Level.Ordinal.ToString(CultureInfo.InvariantCulture) + "\",\n"
+ "\"facility\": " + "\"" + "NLog Android Test" + "\",\n"
+ "\"file\": " + "\"" + Environment.CurrentDirectory + "AndroidApp" + "\",\n"
+ "\"line\": " + "\"" + "123" + "\",\n"
+ "\"Userdefinedfields\": " + "{}" + "\n"
+ "}");
requestWriter.Close();
LastResponseMessage = (HttpWebResponse) request.GetResponse();
}
示例11: ConvertFormat
public static void ConvertFormat(string strInputFile, string strOutputFile)
{
StreamReader sr = new StreamReader(strInputFile);
StreamWriter sw = new StreamWriter(strOutputFile);
string strLine = null;
while ((strLine = sr.ReadLine()) != null)
{
strLine = strLine.Trim();
string[] items = strLine.Split();
foreach (string item in items)
{
int pos = item.LastIndexOf('[');
string strTerm = item.Substring(0, pos);
string strTag = item.Substring(pos + 1, item.Length - pos - 2);
sw.WriteLine("{0}\t{1}", strTerm, strTag);
}
sw.WriteLine();
}
sr.Close();
sw.Close();
}
示例12: Main
static void Main(string[] args)
{
using (StreamWriter str = new StreamWriter(args[0]))
{
int a = Convert.ToInt32(args[1]);
int b = Convert.ToInt32(args[2]);
str.WriteLine("Parameters:");
str.WriteLine(a);
str.WriteLine(b);
int min;
if (a > b)
min = b;
else
min = a;
int i = min;
int c = 0;
while (i>0&&c==0)
{
if ((a % i == 0) && (b % i == 0))
c = i;
i--;
}
//c = 0;
str.WriteLine("Answers:");
str.WriteLine(Convert.ToString(c));
//str.WriteLine(a);
}
}
示例13: WriteToFSLocation
private void WriteToFSLocation(string path, string value)
{
using (StreamWriter sw = new StreamWriter(path))
{
sw.Write(value);
}
}
示例14: SaveTo
public static void SaveTo(string filename, MailAccess mailAccess) {
using (var streamWriter = new StreamWriter(filename, false, Encoding.UTF8)) {
streamWriter.WriteLine(mailAccess.Server);
streamWriter.WriteLine(mailAccess.Username);
streamWriter.WriteLine(mailAccess.Password);
}
}
示例15: Init
public void Init()
{
srStrokes = new StreamReader(opt.StrokesFileName);
srTypes = new StreamReader(opt.StrokesTypesFileName);
srCedict = new StreamReader(opt.CedictFileName);
swOut = new StreamWriter(opt.OutFileName);
}