C# 文件处理:在可执行文件所在的目录中创建文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11967302/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C# File Handling: Create file in directory where executable exists
提问by darnir
I am creating a standalone application that will be distributed to many users. Now each may place the executable in different places on their machines.
I wish to create a new file in the directory from where the executable was executed. So, if the user has his executable in :
我正在创建一个独立的应用程序,它将分发给许多用户。现在每个人都可以将可执行文件放在他们机器上的不同位置。
我希望在执行可执行文件的目录中创建一个新文件。所以,如果用户有他的可执行文件:
C:\exefile\
The file is created there, however if the user stores the executable in:
该文件是在那里创建的,但是如果用户将可执行文件存储在:
C:\Users\%Username%\files\
the new file should be created there.
新文件应该在那里创建。
I do not wish to hard code the path in my application, but identify where the executable exists and create the file in that folder. How can I achieve this?
我不想在我的应用程序中对路径进行硬编码,而是确定可执行文件的存在位置并在该文件夹中创建文件。我怎样才能做到这一点?
采纳答案by Tigran
Never create a file into the directory where executable stays. Especially with the latest OSes available on the market, you can easily jump into the security issues, on file creation. In order to guranteethe file creation process, so your data persistancy too, use this code:
永远不要在可执行文件所在的目录中创建文件。特别是使用市场上可用的最新操作系统,您可以轻松地处理文件创建方面的安全问题。为了保证文件创建过程,因此您的数据持久性也是如此,请使用以下代码:
var systemPath = System.Environment.
GetFolderPath(
Environment.SpecialFolder.CommonApplicationData
);
var complete = Path.Combine(systemPath , "files");
This will generate a path like C:\Documents and Settings\%USER NAME%\Application Data\filesfolder, where you guaranteedto have a permission to write.
这将生成一个类似C:\Documents and Settings\%USER NAME%\Application Data\files 文件夹的路径,您保证在其中具有写入权限。
回答by Saeed Amiri
Just use File.Create:
只需使用File.Create:
File.Create("fileName");
This will create file inside your executable program without specifying the full path.
这将在您的可执行程序中创建文件而不指定完整路径。
回答by bizl
string path;
path = System.IO.Path.GetDirectoryName(
System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase );
MessageBox.Show( path );
回答by Steve Smith
You can get the full path to your new file with:
您可以使用以下命令获取新文件的完整路径:
string path = Path.GetDirectoryName(Application.ExecutablePath) + "\mynewfile.txt"

