读取空文本文件问题 [英] Reading an empty text file problem
问题描述
朋友们,
作为我正在开发的软件的一部分,通过安装安装将一个空的文本文件("filex.txt")放入与可执行文件相同的文件夹中.在软件注册时,我将激活状态(只是一个字符串)写入此文件,并且在每次启动时,我都会读取此文件的内容以验证注册.问题是,当我运行该软件时出现错误,因此我将该位隔离到测试项目中,但仍然出现错误.我捕获到的异常消息说:对象引用未设置为对象的实例".我在测试项目中尝试过的一些代码如下所示:
Hi friends,
As part of a software I am working on, an empty text file("filex.txt") is put into the same folder as the executable by setup installation. I write the activation status(which is just a string) to this file on registration of the software and at every start-up, I read the content of this file to verify registration. The problem is that I get an error when I run that bit of the software so I isolated that bit into a test project and still get an error. The Exception message that I caught says: "Object Reference not set to an instance of an object". The bit of code I tried in the test project is shown below:
//create a streamreader for the filex.txt file
StreamReader reader = new StreamReader(pathfu);
try
{
string rline = reader.ReadLine();
MessageBox.Show(rline.Trim());
MessageBox.Show("This was successful, Thank you");
}
catch (Exception ex)
{
MessageBox.Show("The error is: " + ex.Message);
}
finally
{
reader.Close();
}
推荐答案
尝试一下:
Try this:
if (reader != null)
{
string rline = reader.ReadLine();
if (!string.IsNullOrEmpty(rline))
{
MessageBox.....
}
}
尝试:
string rline = reader.ReadLine();
if (rline != null)
{
MessageBox.Show(rline.Trim());
MessageBox.Show("This was successful, Thank you");
}
如果您查看 StreamReader.ReadLine [
If you look at StreamReader.ReadLine[^] it returns null if the end of the file is encountered.
ReadLine()
方法的工作方式类似于也等于0
和ReadBuffer()
方法0
,然后是ReadLine()
方法return
null
.
结果,您正在null
到rline
.
因此很明显,我们无法从空对象调用方法(在本例中为Trim(
).
这可能会有所帮助,
ReadLine()
method ofStreamReader
class
works like, if thecharLen
andcharPos
(private members of theStreamReader
class) is equal to0
andReadBuffer()
method0
as well, thenReadLine()
methodreturn
null
.
As a result You are gettingnull
torline
.
So it is clear that we cannt call a method( in this caseTrim(
) ) from a null object.
It might be helpful,
class Program
{
static void Main(string[] args)
{
ReadFromFile("C:\\Temp\\Test2.txt");
}
public static void ReadFromFile(string fileToRead)
{
if (File.Exists(fileToRead))
{
using (StreamReader reader = new StreamReader(fileToRead))
{
string lineOfData = default(string);
if ((lineOfData = reader.ReadLine()) != null)
{
var rr = lineOfData.Trim();
}
}
}
}
}
:)
:)
这篇关于读取空文本文件问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!