我想保存到这样的文件:
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();
}
我不确定为什么会这样。感谢
答案 0 :(得分:2)
您需要单独指定文件名,目录,但不足以创建文件:
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对象将封装的文件的相对或绝对路径。
答案 1 :(得分:2)
你的'路径是一个目录,但 System.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 \ Consol eApplication15 \ BIN \调试\ A.TXT