可执行文件的目录路径

时间:2016-09-06 14:20:59

标签: c# winforms directory exe executable

您好我正在尝试使用我的第一个Windows窗体应用程序可执行文件中的文本文档创建目录文件,但这里有些错误:

我希望将其与其他本地用户计算机的exe文件一起使用:

string dir = @"C:\Users\Public\AppData\Roaming\AppFolder\document.txt"; 
if (!Directory.Exists(dir))
{
   Directory.CreateDirectory(Path.GetDirectoryName(dir));
   var stream = File.CreateText(dir);
}

但我得到了这个:

  

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

     

其他信息:进程无法访问该文件   'C:\用户\公用\应用程序数据\漫游\ AppFolder \ doc.txt'   因为它正被另一个进程使用。

3 个答案:

答案 0 :(得分:0)

我猜你需要发出可以在其他地方访问的流的命令

stream.Flush();
stream.Close();

答案 1 :(得分:0)

尝试拥抱使用CreateText语句包含using。因此在使用后关闭。 File.CreateText将创建该文件,但它将一直打开,直到它将被关闭。试图打开它两次将导致IOException

此代码段是https://msdn.microsoft.com/de-de/library/system.io.file.createtext(v=vs.110).aspx

示例的一部分
    string path = @"c:\temp\MyTest.txt";
    if (!File.Exists(path)) 
    {
        // Create a file to write to.
        using (StreamWriter sw = File.CreateText(path)) 
        {
            sw.WriteLine("Hello");
            sw.WriteLine("And");
            sw.WriteLine("Welcome");
        }   
    }

答案 2 :(得分:0)

要在AppData Roaming文件夹中访问/创建文件/目录,您必须执行以下操作

 // The folder for the roaming current user 
string folder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);

// Combine the base folder with your specific folder....
string specificFolder = Path.Combine(folder, "YourSpecificFolder");

// Check if folder exists and if not, create it
if(!Directory.Exists(specificFolder)) 
    Directory.CreateDirectory(specificFolder);
相关问题