Ant*_*tin 3 c# directory file-io file streamwriter
这就是我在我的文件上创建和编写的内容:
Create_Directory = @"" + path;
Create_Name = file_name;
private void Create_File(string Create_Directory, string Create_Name )
{
string pathString = Create_Directory;
if (!System.IO.Directory.Exists(pathString)) { System.IO.Directory.CreateDirectory(pathString); }
string fileName = Create_Name + ".txt";
pathString = System.IO.Path.Combine(pathString, fileName);
if (!System.IO.File.Exists(pathString)) { System.IO.File.Create(pathString); }
///ERROR BE HERE:
System.IO.StreamWriter file = new System.IO.StreamWriter(pathString);
file.WriteLine(Some_Method(MP.Mwidth, MP.Mheight, MP.Mtype, "" ));
file.Close();
}
Run Code Online (Sandbox Code Playgroud)
这里的问题,我整天都在争吵,就是在我创建文件后编写文件.所以,我的程序创建一个文件就好了,然后在写之前发出错误:
"mscorlib.dll中发生了'System.IO.IOException'类型的未处理异常"
"附加信息:该进程无法访问文件'D:\ Projects\Project 15\Project 15\world\world maps\A.txt',因为它正由另一个进程使用."
有趣的是,当我再次运行程序并尝试创建一个已经存在的文件时,正如您所看到的,它会跳过文件创建,转到编写并且工作正常,我真的希望我的程序创建文件并在没有文件的情况下编写不得不重新运行...我在这里看不到什么?:S
问题是File.Create返回一个打开的Stream,你永远不会关闭它.在您创建文件时,该文件(由您)"正在使用" StreamWriter.
话虽这么说,你不需要"创建"文件. StreamWriter会自动为你做.只需删除此行:
if (!System.IO.File.Exists(pathString)) { System.IO.File.Create(pathString); }
Run Code Online (Sandbox Code Playgroud)
一切都应该像书面一样工作.
请注意,我会稍微重写一下,以使其更安全:
private void Create_File(string directory, string filenameWithoutExtension )
{
// You can just call it - it won't matter if it exists
System.IO.Directory.CreateDirectory(directory);
string fileName = filenameWithoutExtension + ".txt";
string pathString = System.IO.Path.Combine(directory, fileName);
using(System.IO.StreamWriter file = new System.IO.StreamWriter(pathString))
{
file.WriteLine(Some_Method(MP.Mwidth, MP.Mheight, MP.Mtype, "" ));
}
}
Run Code Online (Sandbox Code Playgroud)
您也可以使用File.WriteAllText或类似的方法来避免以这种方式创建文件.使用using块保证文件将被关闭,即使Some_Method引发异常也是如此.