StreamWriter无法在C#中工作

前端之家收集整理的这篇文章主要介绍了StreamWriter无法在C#中工作前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
这段代码在VS 2010中完美运行.现在我已经拥有了VS 2013,它不再写入该文件.它没有错误或任何东西. (我在记事本中收到警告,说明文件已更新,但没有写入.)

这对我来说都很好看.有任何想法吗?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            String line;
            try
            {
                //Pass the file path and file name to the StreamReader constructor
                StreamReader sr = new StreamReader("C:\\Temp1\\test1.txt");
                StreamWriter sw = new StreamWriter("C:\\Temp2\\test2.txt");

                //Read the first line of text
                line = sr.ReadLine();

                //Continue to read until you reach end of file
                while (line != null)
                {
                    //write the line to console window
                    Console.WriteLine(line);
                    int myVal = 3;
                    for (int i = 0; i < myVal; i++)
                    {
                        Console.WriteLine(line);
                        sw.WriteLine(line);
                    }
                    //Write to the other file
                    sw.WriteLine(line);
                    //Read the next line
                    line = sr.ReadLine();
                }

                //close the file
                sr.Close();
                Console.ReadLine();
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception: " + e.Message);
            }
            finally
            {
                Console.WriteLine("Executing finally block.");
            }
        }
    }
}

解决方法

你需要在写入后Flush()StreamWriter.

默认情况下,StreamWriter是缓冲的,这意味着它在收到Flush()或Close()调用之前不会输出.

你也可以尝试这样关闭它:

sw.Close();  //or tw.Flush();

你也可以看看StreamWriter.AutoFlush Property

Gets or sets a value indicating whether the StreamWriter will flush
its buffer to the underlying stream after every call to
StreamWriter.Write.

另一个现在非常流行和推荐的选项是使用using statement来照顾它.

Provides a convenient Syntax that ensures the correct use of
IDisposable objects.

例:

using(var sr = new StreamReader("C:\\Temp1\\test1.txt"))
using(var sw = new StreamWriter("C:\\Temp2\\test2.txt"))
{
   ...
}

猜你在找的C#相关文章