文本文件中C#中的StreamWriter限制 [英] StreamWriter limit in C# in text file

查看:400
本文介绍了文本文件中C#中的StreamWriter限制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含100行的数组列表. 当我尝试将其导出到文本文件(txt)时,输出仅为84行,它停在第84行的中间. 当我查看文件大小时,它恰好显示了4.00KB,好像流写入器存在某种限制.我尝试使用其他参数等,但是它一直在发生.

I have an array list which contains 100 lines. When i try to export it into a text file (txt), the output is only 84 lines and it stops in the middle of the 84th line. When I looked at the file size it showed exactly sharp 4.00KB as if there is some kind of a limit to the stream writer. I tried using different parameters etc. but it kept happening.

这是代码:

FileStream fs = new FileStream(path, FileMode.Create);

        StreamWriter sw = new StreamWriter(fs);
        ArrayList chartList = GetChart(maintNode);

        foreach (var line in chartList)
        {
            sw.WriteLine(line);
        }

        fs.Close();
        Console.WriteLine("Done");

感谢您的帮助!

推荐答案

您需要调用StreamWriter.Flush或将StreamWriter.AutoFlush设置为true.就是说,如果您使用using陈述,那么一切都会正常运行.

You need to call StreamWriter.Flush or set StreamWriter.AutoFlush to true. That said, if you use using statment, everything should work fine.

using(StreamWriter sw = new StreamWriter(fs))
{
    ArrayList chartList = GetChart(maintNode);    
    foreach (var line in chartList)
    {
        sw.WriteLine(line);
    }
}

使用语句调用Dispose,这会将缓冲区刷新到FileStream,并关闭文件流.因此,您无需手动关闭它.

Using statement calls Dispose which will flush the buffer to the FileStream and also closes the file stream. So you don't need to close it manually.

然后,我建议使用List<T>而不是ArrayList. ArrayList不应使用,它不是类型安全的,如果您使用的是.Net2.0或更高版本,则应避免使用该语言.

Then I recommend List<T> over ArrayList. ArrayList shouldn't be used, it is not type safe and should be avoided if you're in .Net2.0 or greater.

还可以考虑使用 File.WriteAllLines 方法,因此您不需要这么多代码行.一切都由WriteAllLines方法本身管理.

Also consider using File.WriteAllLines method, so that you don't need these many lines of code. Everything is managed by WriteAllLines method itself.

这篇关于文本文件中C#中的StreamWriter限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆