filestream,streamreader和streamwriter的问题

时间:2011-10-07 14:27:00

标签: 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块之外声明,但在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;
        }
    }

任何帮助都会非常感谢,谢谢。

3 个答案:

答案 0 :(得分:4)

嗯,它们已被声明但未分配......所以,要么将它们设置为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;
}

答案 1 :(得分:3)

您需要在顶部为变量赋值,即使它只是null

FileStream   file     = null;
StreamReader file_in  = null;
StreamWriter file_out = null;

答案 2 :(得分:0)

在关闭文件之前,请尝试刷新输出流和文件。

 file_out.Flush();
 file.Flush(); // may be redundant but won't hurt