文件编写器失败

时间:2018-10-16 17:18:06

标签: c# .net file-io

我有以下代码:

private void Write(string path, string txt)
{
    string dir =Path.GetDirectoryName(path);
    try
    {
        if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); }
        if (!File.Exists(path))
        {
            File.Create(path).Dispose();
            using (TextWriter tw = new StreamWriter(path))
            {
                tw.WriteLine(txt);
                tw.Close();
            }
        }
        else
        {
            using (TextWriter tw = new StreamWriter(path, true))
            {
                tw.WriteLine(txt);
            }
        }
    }
    catch (Exception ex)
    {
        //Log error;
    }
}
在路径参数中传递

Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)+"\\html\\Static_1.html",并为txt参数传递一些html文本。代码在File.Create()处失败。我收到以下错误:

  

找不到文件'C:\ Users \ Xami Yen \ Documents \ html \ Static_1.html

此代码有什么问题?无法弄清楚。

2 个答案:

答案 0 :(得分:1)

MSDN文档: spring: sleuth: propagation-keys: trId 方法将创建一个新文件,将内容写入该文件,然后关闭该文件。如果目标文件已经存在,它将被覆盖。

此外,请确保您对新创建的文件夹具有“写”权限。

File.WriteAllText

答案 1 :(得分:1)

尝试一下:

private void Write(string path, string txt, bool appendText=false)
{
    try
    {
        string directory = Path.GetDirectoryName(path);

        if (!Directory.Exists(directory))
        {
            Directory.CreateDirectory(directory);
        }

        if (appendText)
        {
            // Appends the specified string to the file, creating the file if it does not already exist.
            File.AppendAllText(path, txt);
        }
        else
        {
            // Creates a new file, write the contents to the file, and then closes the file.
            // If the target file already exists, it is overwritten.
            File.WriteAllText(path, txt);
        }
    }
    catch (Exception ex)
    {
        //Log error
        Console.WriteLine($"Exception: {ex}");
    }
}