我有以下代码:
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"
在path参数中传递,并为txt参数传递一些html文本。代码在File.Create()
失败了。我收到以下错误:
找不到文件'C:\ Users \ Xami Yen \ Documents \ html \ Static_1.html
这段代码有什么问题?无法弄清楚。
MSDN文档:File.WriteAllText
方法创建一个新文件,将内容写入该文件,然后关闭该文件。如果目标文件已存在,则会被覆盖。
另外,请确保您对新创建的文件夹具有写入权限。
private void Write(string path, string txt)
{
var dir = Path.GetDirectoryName(path);
try
{
if (!Directory.Exists(dir)) Directory.CreateDirectory(dir);
File.WriteAllText(path, txt);
}
catch (Exception ex)
{
//Log error;
}
}
试试这个:
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}");
}
}