在C#中读取文本文件 [英] Reading a text file in C#
问题描述
我正在使用下面给出的代码在C#中读取文本文件,理想情况下这应该逐个读取每一行,但问题是在阅读时跳过每个备用行,我无法理解问题是什么是。请对任何解决方案有任何帮助。
string fileName = < span class =code-string> @ C:\NewTextDoc.txt;
string str = string .Empty;
if (File.Exists(fileName))
{
StreamReader sr = new StreamReader(fileName);
String 行;
while (sr.ReadLine()!= null )
{
line = sr.ReadLine();
if (line.Trim()!= string .Empty)
{
s = line.substring( 1 , 4 );
}
}
}
else
{
s = 文件不存在;
}
return s;
你正在做什么
while (sr.ReadLine()!= null )
消耗一条线,然后你再次line = sr.ReadLine();
,消耗另一条线,但只第二个读数存储在sr
。
您可以将其更改为此;
while ((line = sr.ReadLine())!= null )
{
if (line.Trim()!= string .Empty)
{
s = line.substring( 1 , 4 );
}
}
或者只是使用FileInfo.ReadAllLines
除非你的文件非常庞大。
希望这会有所帮助,
Fredrik
< blockquote>首先你做的是:
while (sr.ReadLine()!= null )
文件中的指针移动到下一行。然后你做
line = sr.ReadLine();
所以指针再次移动。这会带给你一段时间...
当你认为你读到的文件减半时宣布。
你需要阅读文件逐行?
你可以根据 MSDN [ ^ ]
您实际上正在调用StreamReader.Readline
方法两次 (都在而
条件和line = sr.ReadLine;
语句中,但只使用其中一个返回价值)。
如文档 [ ^ ]代码示例,您可以使用StreamReader.Peek
方法来检查文件结束条件:
而(sr.Peek()> = 0 )
{
line = sr.ReadLine();
// ..
}
I was reading a text file in C# by code as given below , ideally this should read each and every line one by one but the problem is every alternate line is skipped while reading , I'm not able to understand what the problem is . Please can any help with any solution.
string fileName = @"C:\NewTextDoc.txt";
string str = string.Empty;
if (File.Exists(fileName))
{
StreamReader sr = new StreamReader(fileName);
String line;
while (sr.ReadLine() != null)
{
line = sr.ReadLine();
if (line.Trim() != string.Empty)
{
s = line.substring(1,4) ;
}
}
}
else
{
s = "File does not exists";
}
return s;
You're doing
while(sr.ReadLine() != null)
That consumes a line, then you're doingline = sr.ReadLine();
again, that consumes another line, but only the second read is stored insr
.
You could change it to this;
while ((line = sr.ReadLine()) != null) { if (line.Trim() != string.Empty) { s = line.substring(1,4) ; } }
Or maybe just useFileInfo.ReadAllLines
unless your file is absolutely massive in size.
Hope this helps,
Fredrik
first you do in the while:while (sr.ReadLine() != null)The pointer in the file moves to the next line. And then you do
line = sr.ReadLine();so the pointer is moved again. which brings you to the while...
That declares while you think you read halve the file.
do you need to read the file line by line?
You can read it very simple according to MSDN[^]
You are actually callingStreamReader.Readline
method twice (both in thewhile
condition and in theline = sr.ReadLine;
statement, but using only one of the return values).
As in the documentation[^] code sample, you may useStreamReader.Peek
method to check for the End Of File condition:
while (sr.Peek() >= 0) { line = sr.ReadLine(); //.. }
这篇关于在C#中读取文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!