微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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"))
{
   ...
}

原文地址:https://www.jb51.cc/csharp/97144.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐