StreamReader找不到文件(因为它没有被创建)

时间:2017-10-13 14:17:55

标签: c# file streamreader streamwriter

我正在尝试为进一步写入和读取创建一个文件。

我使用Directory.CreateDirectory和File.Create,但是没有创建路径和文件。

在我在下面显示的部分页面上,我检查文件是否存在,如果没有,我创建一个文件。在第二页(我在这里没有显示)我使用StreamWrite向文件添加新行。保存后,第一页将再次聚焦并列出文件的内容(本研究中只有一行)。

以下是我对相关部分的代码:

public async Task ReadFileAsync()
    {


        string directoryName = Path.GetDirectoryName(@"C:\Users\...\DataBase\");
        Task.Run(async() => Directory.CreateDirectory(directoryName));
        Task.Run(async() => File.Create(directoryName + "ProductsDatabase.txt"));

        //code for reading from file
        string path = (directoryName + "ProductsDatabase.txt");

        using (StreamReader ProductsDatabaseRead = new StreamReader(File.OpenRead(path)))
        {
            ProductOneTextBlock.Text = ProductsDatabaseRead.ReadLine();

        }
        if (ProductOneTextBlock.Text == "")
            {
            ProductOneTextBlock.Text = "Nothing to show";
            }
    }

未创建文件和文件夹。

我没有收到任何错误。

如果解决方案文件夹中有READ ONLY文件夹,我也尝试了驱动器上的不同文件夹。没有区别。

有人可以帮忙吗? (我发现了许多关于这个问题的线索,但在这里我无法解决这个问题。

未创建物理文件。

当我尝试写入它(从另一个页面)时,我收到错误的文件无法找到(因为它确实不存在)。

似乎程序在某处介于

之间
Task.Run(async() => Directory.CreateDirectory(directoryName));
        Task.Run(async() => File.Create(directoryName + "ProductsDatabase.txt"));

using (StreamReader ProductsDatabaseRead = new StreamReader(File.OpenRead(path)))
        {
            ProductOneTextBlock.Text = ProductsDatabaseRead.ReadLine();

        }

,因为即使ProductsDatabaseRead为null,TextBlock也不会更新。

如果我把

ProductOneTextBlock.Text = "Nothing to show";

方法的开头,TextBlock得到更新。

那么,为什么

using (StreamReader ProductsDatabaseRead = new StreamReader(File.OpenRead(path)))

不起作用?

2 个答案:

答案 0 :(得分:4)

您不等待Task.Run完成。您的目录创建,文件创建以及尝试打开"您认为新创建的文件"坏了。这就是为什么你可能无法打开文件的原因(此时它仍然不存在)。

Task.Run返回完成工作后将完成的任务。你需要等待完成。

答案 1 :(得分:0)

public void ReadFile()
{
    string folderPath = @"C:\Users\patri\source\repos\DietMate\";
    string fileName = "ProductsDatabase.txt";
    string fullPath = Path.Combine(folderPath, fileName);

    //insert code to check whether file exists.
    // use Exists()    
    if (!Directory.Exists(folderPath))
    {
        Directory.CreateDirectory(folderPath);
        File.Create(fullPath);
    }

    //if yes, follow with code below
    //insert code for reading from file
    using (StreamReader ProductsDatabaseRead = new StreamReader(fullPath))
    {
        ProductTest.Text = ProductsDatabaseRead.ReadLine();
    }
}
相关问题