在.txt文件上编写arraylist时需要帮助 [英] need help in writing arraylist on a .txt file

查看:61
本文介绍了在.txt文件上编写arraylist时需要帮助的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码

this is my code

FileStream ftoken = new FileStream("c:\\Tokens.txt",FileMode.Create);
ftoken.Close();
Regex re = new Regex(@"([\.\=\(\)\ \''])", RegexOptions.IgnorePatternWhitespace);
string classPart = " ";
ArrayList tokenArray = new ArrayList();
StreamWriter write = new StreamWriter("c:\\Tokens.txt");
for (int i = 0; i < richTextBox1.Lines.Length; i++)
{
     string[] splitString = re.Split(richTextBox1.Lines[i]);
     foreach(string s in splitString)
     {
           string token = classPart + " " + s + " " + (i + 1).ToString();
           tokenArray.Add(token);
     }
}
     foreach (object line in tokenArray)
     {
          write.WriteLine(line);
     }



我没有收到任何错误,但是token.txt文件没有任何内容:(



i dont get any error but token.txt file has nothing :(

推荐答案

除了罗伯(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> ;,或者最好还是只做写而不要使用集合.
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.


这篇关于在.txt文件上编写arraylist时需要帮助的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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