2013-03-19 83 views
3

这是我做的创建和我的文件中写道:C#文件处理 - 创建一个文件,并打开

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(); 
    } 

这里的问题,我已经奋战了整整一天,之后我写文件创造它。所以,我的程序创建一个文件就好了,然后写入之前给出了一个错误:

“类型‘System.IO.IOException’未处理的异常出现在mscorlib.dll”

“附加信息:进程无法访问文件'D:\ Projects \ Project 15 \ Project 15 \ world \ world maps \ A.txt',因为它正在被另一个进程使用。“有趣的是,当我再次运行程序并尝试创建一个已经存在的文件时,就像你看到的那样,它跳过了文件创建,写入和工作正常,我真的希望我的程序创建文件和写入,而不必重新运行它...我在这里没有看到什么? :S

回答

5

问题是File.Create返回一个打开的Stream,并且您从不关闭它。该文件在您创建StreamWriter时正在使用(由您)。

这就是说,你不需要“创建”文件。 StreamWriter会自动为你做。只删除这一行:

if (!System.IO.File.Exists(pathString)) { System.IO.File.Create(pathString); } 

而且一切都应该写作。

注意,我不过稍显改写这个,使其更安全:

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, ""));  
    } 
} 

您也可以只使用File.WriteAllText或类似的方法来避免创建的文件这种方式。使用using块可保证文件将被关闭,即使Some_Method引发异常。

+0

我可以在这里看到很多有用的建议,我会尽力它出来了,我认为这会做:) – 2013-03-19 00:30:38

+0

一个问题,但如果我的文件已经存在,会发生什么,我试图做出另一个同名的? 编辑:我发现了,它只是重写它,幸运的是我已经设法将我的旧代码与你融合在一起,并找到了适合我的东西,谢谢大家:D – 2013-03-19 00:34:59

2

您可以使用File类,因为它包装了很多工作,为您

例子:

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); } 

    pathString = System.IO.Path.Combine(pathString, Create_Name + ".txt"); 
    File.WriteAllText(fileName, Some_Method(MP.Mwidth, MP.Mheight, MP.Mtype, "")); 
} 
+0

感谢您的信息:) – 2013-03-19 00:40:20

0
static void Main(string[] args) 
     { 
      FileStream fs = new FileStream("D:\\niit\\deep.docx", FileMode.Open, FileAccess.Read); 
      StreamReader sr = new StreamReader(fs); 
      sr.BaseStream.Seek(0, SeekOrigin.Begin); 
      string str = sr.ReadLine(); 
      Console.WriteLine(str); 
      Console.ReadLine(); 

     } 
+0

上面的程序阅读并打开已在计算机内创建的文件。 – 2014-07-22 20:19:28