我正试图保存到这样的文件:
string path = AppDomain.CurrentDomain.BaseDirectory;
fs = new System.IO.FileStream(path, System.IO.FileMode.Append, System.IO.FileAccess.Write);
但是我得到了DirectoryNotFoundException,尽管目录存在。
这是的方法
public static void WriteToFile(string s)
{
string path = AppDomain.CurrentDomain.BaseDirectory;
fs = new System.IO.FileStream(path, System.IO.FileMode.Append, System.IO.FileAccess.Write);
sw = new System.IO.StreamWriter(fs);
sw.WriteLine(s);
sw.Flush();
sw.Close();
fs.Close();
}
我不知道为什么会发生这种事。感谢
您需要指定文件名,仅目录不足以创建文件:
public static void WriteToFile(string s, string fileName)
{
string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, fileName);
fs = new System.IO.FileStream(path, System.IO.FileMode.Append, System.IO.FileAccess.Write);
sw = new System.IO.StreamWriter(fs);
sw.WriteLine(s);
sw.Flush();
sw.Close();
fs.Close();
}
用法:
WriteToFile("Some Text To Write", "SampleFileName.txt");
以下是的文档
public FileStream(string path, FileMode mode, FileAccess access);
参数:path:当前FileStream对象将封装的文件的相对或绝对路径。
Your'路径是一个目录,但系统。IO.FileStream.FileStream(字符串路径,FileMode模式,FileAccess访问)需要一个文件路径,所以我修改你的代码如下:
public static void WriteToFile(string s)
{
string path = AppDomain.CurrentDomain.BaseDirectory + "a.txt";
var fs = new System.IO.FileStream(path, System.IO.FileMode.Append, System.IO.FileAccess.Write);
var sw = new System.IO.StreamWriter(fs);
sw.WriteLine(s);
sw.Flush();
sw.Close();
fs.Close();
Console.WriteLine(path);
Console.ReadKey();
}
输出:d: \users\zwguo\documents\visual studio 2013\Projects\ConsoleApplication15\ConsoleApplication15\bin\Debug\a.txt