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

标签 c# file filestream streamreader streamwriter

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

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/

相关文章:

c# - 如何在 C# 中将大文件拆分成 block ?

c# - 将 ASP.NET MVC 3 应用程序部署到 IIS

c# - C# 中自己的 DSL 的代码解析器

c# - 如何使在 wpf 窗口中运行的应用程序忽略单击或鼠标事件

javascript - P5Js修改本地文件,例如json或xml或表

c - 使用 fscanf 从文件中读取字符串和整数

java - 读取文本文件并添加到列表时出现内存不足错误

c++ - 我必须以 [ios::binary] 模式打开文件才能获取其大小吗?

c# - 客户可以在生产后更改环境IsDevelopment