且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在.txt文件上编写arraylist时需要帮助

更新时间:2023-11-24 09:09:10

除了罗伯(Rob)所说的那样:您需要使用using语句:

In addition to what Rob said: you need to use the using statement:

using (StreamWriter writer = new StreamWriter("my_file_name.txt")) {
    writer.Write("blah blah blah");
    //...
} //at this point, writer.Dispose will be called even if an exception was thrown



您应该对实现接口System.IDisposable的所有临时对象使用此构造.它完全等效于在代码的最终"部分的对象中实现的try-finally块调用IDisposable.Dispose.
参见:
http://msdn.microsoft.com/en-us/library/system.idisposable.aspx [^ ],
http://msdn.microsoft.com/en-us/library/yh598w02.aspx [ ^ ],
http://msdn.microsoft.com/en-us/library/system.io. streamwriter.aspx [^ ].

—SA



You should use this construct for all temporary object implementing the interface System.IDisposable. It is fully equivalent to a try-finally block calling IDisposable.Dispose implemented in the object in the "finally" section of code.
See:
http://msdn.microsoft.com/en-us/library/system.idisposable.aspx[^],
http://msdn.microsoft.com/en-us/library/yh598w02.aspx[^],
http://msdn.microsoft.com/en-us/library/system.io.streamwriter.aspx[^].

—SA


这真是疯狂的代码!首先,您不需要顶部的FileStream来创建文件,StreamWriter会为您完成此操作.您是否在WriteLine上设置了一个断点,以检查是否有任何内容被写入?

可能的问题是您没有关闭StreamWriter.很有可能您编写的内容位于缓冲区中,直到您将Flush()或Close()流添加到磁盘后,该内容才会被放入磁盘.

另外,不要使用ArrayList,这已成为过去.使用List< string&gt ;,或者***还是只做写而不要使用集合.
That''s a crazy bit of code! Firstly, you don''t need the FileStream at the top to create the file, the StreamWriter will do that for you. Did you put a break point on the WriteLine to check if anything is getting written?

Probably the problem is that you don''t close the StreamWriter. It could well be that what you''ve written is sitting in a buffer and will not get put to disk until you Flush() or Close() the stream.

Also, don''t use an ArrayList, that''s a thing of the past. Use a List<string>, or better still just do the write rather than use a collection at all.