gpt4 book ai didi

c# - 文件流、streamreader 和 streamwriter 的问题

转载 作者:太空宇宙 更新时间:2023-11-03 18:42:09 24 4
gpt4 key购买 nike

我的第一个问题是如果我以这种方式声明我的文件流等

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 block 之外但在 main 中声明,因此它们应该存在于 main 中。

我的另一个问题是,如果我删除 try/catch block 并将流声明为一行(例如: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;
}

关于c# - 文件流、streamreader 和 streamwriter 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7688658/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com