C#文件处理:在可执行文件存在的目录中创建文件 [英] C# File Handling: Create file in directory where executable exists

查看:103
本文介绍了C#文件处理:在可执行文件存在的目录中创建文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个将分发给许多用户的独立应用程序。现在,每个人都可以将可执行文件放在机器上的不同位置。

我希望在执行可执行文件的目录中创建一个新文件。所以,如果用户有他的可执行文件:

  C:\exefile\ 



这个文件是在那里创建的,但是如果用户把可执行文件保存在:

  C:\ Users \%Username%\files\ 





我不希望在我的应用程序中硬编码路径,而是确定可执行文件存在的位置,然后创建文件该文件夹。我怎么能做到这一点?

解决方案

切勿在可执行文件保留的目录中创建文件。特别是市场上最新的操作系统,您可以轻松地跳到安全问题,文件创建。
为了保证文件的创建过程,所以你的数据也持续使用这段代码:

  var systemPath = System.Environment。 
GetFolderPath(
Environment.SpecialFolder.CommonApplicationData
);
var complete = Path.Combine(systemPath,files);

这会产生一个像 C:\Documents and Settings\%USER NAME %\ Application Data\files 文件夹,您可以保证有权限写入。


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?

解决方案

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 gurantee the 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\files folder, where you guaranteed to have a permission to write.

这篇关于C#文件处理:在可执行文件存在的目录中创建文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆