文件流、流阅读器和流写入器的问题
本文关键字:问题 文件 | 更新日期: 2023-09-27 18:10:37
我的第一个问题是如果我以这种方式声明我的文件流等
filestream file;
streamreader file_in;
streamwriter file_out;
try
{
file = new filestream("data.txt", FileMode.OpenOrCreate);
file_in = new streamreader(file);
file_out = new streamwriter(file);
}
catch(IOException exc)
{
Console.WriteLine(exc.Message);
}
抛出一个错误,说"使用未分配的局部变量",我觉得很奇怪,因为所有的流都是在try块之外声明的,但在main中,所以它们应该存在于main中。
我的其他问题出现的形式是,如果我删除try/catch块,只是声明流为一行(例如:FileStream file = new FileStream("data.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite);
)我从文件读取确实工作,但我不能写入文件。我的写入文件功能如下:
public bool write_to_file(ref StreamWriter file_out)
{
if (this.is_empty == true)
{
Console.WriteLine("error, there is nothing to write.");
Console.WriteLine("press any key to continue...");
Console.ReadKey();
return false;
}
try
{
string temp = this.is_empty + "," + this.movie_title + "," + this.year_released + "," + this.publisher + "," +
this.length + "," + this.acting_rating + "," + this.music_rating + "," + this.cinematography_rating + "," +
this.plot_rating + "," + this.duration_rating + "," + this.total_rating;
file_out.WriteLine(temp);
return true;
}
catch (IOException exc)
{
Console.WriteLine(exc.Message);
Console.WriteLine("press any key to continue...");
Console.ReadKey();
return false;
}
}
它们被声明了,但是没有赋值…因此,要么将它们设置为null,要么将所有操作放在一起。
try
{
using(var file = new FileStream("data.txt", FileMode.OpenOrCreate))
using(var file_in = new StreamReader(file))
using(var file_out = new StreamWriter(file))
{
// Do your thing
}
}
catch
{
throw;
}
您需要为顶部的变量分配一个值,即使它只是null
FileStream file = null;
StreamReader file_in = null;
StreamWriter file_out = null;
在关闭文件之前,尝试刷新输出流和文件。
file_out.Flush();
file.Flush(); // may be redundant but won't hurt