当前位置: 首页>>代码示例>>C#>>正文


C# IO.StreamWriter类代码示例

本文整理汇总了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          
            
        }
开发者ID:aspose-pdf,项目名称:Aspose.Pdf-for-.NET,代码行数:28,代码来源:ExtractTextFromPageRegion.cs

示例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;
             }
         }
     }
 }
开发者ID:Prizmer,项目名称:tu_teplouchet,代码行数:38,代码来源:CMeter.cs

示例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());
      }
    }
开发者ID:chekiI,项目名称:MediaPortal-2,代码行数:34,代码来源:ServerCrashLogger.cs

示例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));
                }
            }
        }
开发者ID:MSylvia,项目名称:mspriterenderer,代码行数:33,代码来源:GorgonMapExporter.cs

示例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));  
            }
        }
开发者ID:maanshancss,项目名称:ClassLibrary,代码行数:35,代码来源:FileLogger.cs

示例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);
        }
开发者ID:tavenli,项目名称:gaopincai,代码行数:30,代码来源:ExtractData.cs

示例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);
        }
开发者ID:JaanJanno,项目名称:TestExercise,代码行数:25,代码来源:Decrypt.cs

示例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);
            }
        }
开发者ID:Shemetov,项目名称:OneScript,代码行数:29,代码来源:MainWindow.xaml.cs

示例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);
            }
        }
开发者ID:andyhebear,项目名称:HappyQ-WowServer,代码行数:26,代码来源:PacketReader.cs

示例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();
        }
开发者ID:unhappy224,项目名称:NLog.IqMetrix,代码行数:27,代码来源:LumberMillTarget.cs

示例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();
        }
开发者ID:zxz,项目名称:RNNSharp,代码行数:25,代码来源:Program.cs

示例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);
     }
 }
开发者ID:LearningSystem,项目名称:InformationSystem,代码行数:28,代码来源:Program.cs

示例13: WriteToFSLocation

 private void WriteToFSLocation(string path, string value)
 {
     using (StreamWriter sw = new StreamWriter(path))
     {
         sw.Write(value);
     }
 }
开发者ID:mikekberg,项目名称:GIOPL.NET,代码行数:7,代码来源:EdisonDevicePinService.cs

示例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);
     }
 }
开发者ID:slieser,项目名称:sandbox,代码行数:7,代码来源:MailAccessRepository.cs

示例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);
 }
开发者ID:sheeeng,项目名称:Zydeo,代码行数:7,代码来源:WrkCharStats.cs


注:本文中的System.IO.StreamWriter类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。