从头开始读取文件 [英] reading file from begin

查看:107
本文介绍了从头开始读取文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

hi
我正在读取文件,假设我在第9行中,我想再次返回第1行?
我关闭文件并再次打开它是一个好的解决方案吗?
它的文本文件

hi
i am reading a file suppose that i am in line 9 i want return to line 1 again ?
is it good solution that i close file and open it again ??
it''s text file

 StreamReader Readfile = new StreamReader(@op.FileName.ToString());
 while ((Rline = Readfile.ReadLine()) != null)
                    {
                        temp = Rline;
                        temp = temp.Substring(1, 4).Replace(" ", string.Empty);
                        
                        if (Convert.ToInt32(temp) == Convert.ToInt32(textBox3.Text) && Convert.ToDateTime(Rline.Substring(6, 10)) >= InDate)
                        {
                            filewrite.WriteLine(Rline);
                        }
                    }
                progressBar1.Value = 20;
                Readfile.Close();
// here i want to read file again 

推荐答案

您可能会使用 ^ ]方法(您应检查您的实际流是否支持它,请参阅链接页面中的备注" 部分.
You probably might use the Stream.Seek[^] method (you should check if your actual stream supports it, see the "Remarks" section in the linked page.


在大多数情况下,这是一种不好的做法.您只是在阅读,所以为什么还要回来?请记住第一行的阅读结果并继续前进.实际上,如果文件不太大,如果一次阅读所有内容,然后仅使用System.IO.StreamReader.ReadToEnd:
http://msdn.microsoft.com/en-us/library/system. io.streamreader.readtoend.aspx [ ^ ].

现在,请注意以下几点:

您的FileName.ToString告诉了我很多.什么,您看不到文件名已经是字符串吗?

而且,这不是使用StreamReader之类的类型的好模式.它实现了System.IDisposable,因此您可以通过using语句使用它(不要与using声明混淆):

In most cases, this is bad practice. You are only reading, so why would you ever come back? Remember result of the first line reading and go forward. Actually, if the file is not too big, you can gain a lot if you read everything at once and then only manipulate the string, using System.IO.StreamReader.ReadToEnd:
http://msdn.microsoft.com/en-us/library/system.io.streamreader.readtoend.aspx[^].

Now, a couple of notes:

Your FileName.ToString tells me a lot. What, don''t you see that the file name is already a string?

Also, this is not a good pattern of using the types like StreamReader. It implements System.IDisposable, so you can use it via the using statement (not to be confused with using declaration):

using (StreamReader reader = new StreamReader(@op.FileName.ToString())) {
    // use reader here
}   // here, reader.Dispose is automatically called; it will be closed,
    // the stream buffer won't be lost (especially important in case of StreamWriter)


请参阅:
http://msdn.microsoft.com/en-us/library/system.idisposable.aspx [^ ],
http://msdn.microsoft.com/en-us/library/yh598w02%28v = vs.80%29.aspx [ ^ ].

—SA


Please see:
http://msdn.microsoft.com/en-us/library/system.idisposable.aspx[^],
http://msdn.microsoft.com/en-us/library/yh598w02%28v=vs.80%29.aspx[^].

—SA


这篇关于从头开始读取文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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