C#文件处理 - 创建文件并打开

时间:2013-03-19 00:22:53

标签: c# file file-io directory 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();
    }

这里的问题,我一整天都在争吵,就是在创建文件后编写文件。所以,我的程序创建一个文件就好了,然后在写之前发出错误:

“mscorlib.dll中发生了'System.IO.IOException'类型的未处理异常”

“附加信息:进程无法访问文件'D:\ Projects \ Project 15 \ Project 15 \ world \ world maps \ A.txt',因为它正由另一个进程使用。”

有趣的是,当我再次运行程序并尝试创建一个已经存在的文件时,正如您所看到的,它会跳过文件创建,转到编写并且工作正常,我真的希望我的程序创建文件写而不必重新运行...我在这里看不到什么? :S

3 个答案:

答案 0 :(得分: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块也可以保证文件关闭。

答案 1 :(得分: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, ""));
}

答案 2 :(得分: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();

        }