简体   繁体   English

StreamWriter 不会将任何文本写入文件

[英]StreamWriter don't writing any text to file

I wrote some code, which should write to file some text:我写了一些代码,应该写入文件一些文本:

        private static FileStream CreateFile()
        {
            string _fileName = "znaki.txt";

            if(File.Exists(_fileName))
            {
                File.Delete(_fileName);
            }

            FileStream fs = new FileStream(_fileName, FileMode.Create, FileAccess.Write);

            Console.Clear();
            Console.Write("Ile znakok chcesz wygenerowac? >> ");
            int lp;
            lp = Convert.ToInt32(Console.ReadLine());

            Random r = new Random();
            StreamWriter sw = new StreamWriter(fs);
            for (int i = 0; i < lp; i++)
            {
                Console.Clear();
                Console.WriteLine(i + "/" + lp);

                sw.WriteLine("jogurcik");
            }

            return fs;
        }

This code create the file but don't write anything.此代码创建文件但不写入任何内容。 What is wrong with this code?这段代码有什么问题?

Close StreamWriter (as well as FileStream) at the end of the writing routine:在写入例程结束时关闭 StreamWriter(以及 FileStream):

sw.Close();
fs.Close();

MSDN : 微软

You must call Close to ensure that all data is correctly written out to the underlying stream... Flushing the stream will not flush its underlying encoder unless you explicitly call Flush or Close.您必须调用 Close 以确保所有数据正确写入底层 stream... 刷新 stream 不会刷新其底层编码器,除非您显式调用 Flush 或 Close。

PS Alternative way is to use the using statement that helps to close and dispose of IO objects automatically: PS 替代方法是使用有助于自动关闭和处理 IO 对象的using语句:

using (FileStream fs = new FileStream(_fileName, FileMode.Create, FileAccess.Write))
{
    ...
    using (StreamWriter sw = new StreamWriter(fs)) 
    { 
        for (int i = 0; i < lp; i++)
        {
            ...
            sw.WriteLine("jogurcik");
        }
    }
}

In this case you can ommit the close call.在这种情况下,您可以省略 close call。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM