可执行文件的目录路径

Directory path for 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);
}

但我得到了这个:

An unhandled exception of type 'System.IO.IOException' occurred in mscorlib.dll

Additional information: The process cannot access the file 'C:\Users\Public\AppData\Roaming\AppFolder\doc.txt' because it is being used by another process.

我想您需要发出命令才能在其他任何地方访问流

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

尝试用using语句拥抱CreateText。所以在使用后关闭。 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");
        }   
    }

要在 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);