C# Environment.CurrentDirectory 与 System.IO.Directory.GetCurrentDirectory

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19981504/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 16:18:32  来源:igfitidea点击:

Environment.CurrentDirectory vs System.IO.Directory.GetCurrentDirectory

c#.netvb.net

提问by John Bustos

I'm writing a .Net WinForms on and constantly switching between DEBUG and RELEASE configurations and have a few files I need either configuration to be able to get to.

我正在编写 .Net WinForms 并不断在 DEBUG 和 RELEASE 配置之间切换,并且有一些文件我需要任何一种配置才能访问。

What I was thinking to do was to put the files in a common directory in the BIN folder so it would look like this:

我想做的是将文件放在 BIN 文件夹中的公共目录中,因此它看起来像这样:

MyProject/Bin/CommonFiles
MyProject/Bin/Debug
MyProject/Bin/Release

And I was thinking about accessing the files using something along the lines of:

我正在考虑使用以下内容访问文件:

System.IO.Directory.GetParent(System.IO.Directory.GetCurrentDirectory).FullName

My question is if this is dangerous since, from what I've read, System.IO.Directory.GetCurrentDirectorymight change due to the user selecting a new current directory in, say, an open file dialogue box.

我的问题是这是否很危险,因为从我读过的内容来看,System.IO.Directory.GetCurrentDirectory可能会由于用户在打开文件对话框中选择一个新的当前目录而改变。

Should I rather use something along the lines of:

我应该更喜欢使用以下内容:

System.IO.Directory.GetParent(Environment.CurrentDirectory).FullName

ORis there an even better way to get to the /Binfolder so I can move from there or a generally accepted way / location to store files the program usually needs to reach and way to reference that more easily (maybe something that's made to work with any kind of app and not just WinForms)?

或者有没有更好的方法来访问该/Bin文件夹,以便我可以从那里移动或以普遍接受的方式/位置来存储程序通常需要访问的文件以及更轻松地引用该文件的方式(也许可以与任何一种应用程序,而不仅仅是 WinForms)?

采纳答案by John Bustos

Although most of the answers did actually seem to work, the solution offered by Joe above, after quite a bit of tweaking, proved to be the best solution for my situation.

尽管大多数答案似乎确实有效,但上述 Joe 提供的解决方案经过大量调整后,被证明是最适合我的情况的解决方案。



Firstly, the final solution I went with:

首先,我采用的最终解决方案是:

  • Created a Common Filesdirectory (In my case, at the same level as my Bindirectory, but that's not necessary, it'll just explain how the code I'll put up later works)
  • Edited my .vbproj(or `,csproj') file to set all the files in that directory (including sub-directories) as extra resource files for my project
  • Made a second edit to my .vbprojfile to copy all those resource files to my bin\Debug or bin\Release directory at build time.
  • 创建了一个Common Files目录(在我的情况下,与我的Bin目录处于同一级别,但这不是必需的,它只会解释我稍后将放置的代码如何工作)
  • 编辑我的.vbproj(或`,csproj')文件,将该目录(包括子目录)中的所有文件设置为我的项目的额外资源文件
  • 对我的.vbproj文件进行了第二次编辑,以在构建时将所有这些资源文件复制到我的 bin\Debug 或 bin\Release 目录中。


Secondly, how I learned to do this:

其次,我是如何学会这样做的:

  • Joes solution above
  • This linkshows how to be able to add in wildcards to the .vbproj / .csproj files so you can add in full directories at once.
  • This answerwhich shows how to copy the files to my \Bin Directory


Finally, my solution:

最后,我的解决方案:

  • I opened my project.vbproj file
  • Abovethe line <Import Project="$(MSBuildToolsPath)\Microsoft.VisualBasic.targets" />, I added in one new ItemGrouplooking as follows:
  • 我打开了我的 project.vbproj 文件
  • 上面的线<Import Project="$(MSBuildToolsPath)\Microsoft.VisualBasic.targets" />,我在一个新增加的ItemGroup寻找如下:

<ItemGroup> <CommonFiles Include="Common Files\**" /> </ItemGroup>

<ItemGroup> <CommonFiles Include="Common Files\**" /> </ItemGroup>

This loads in all the files (including all sub-folders) and gives I the Build Action CommonFiles

这会加载所有文件(包括所有子文件夹)并为我提供构建操作 CommonFiles

  • Beneaththe line <Import Project="$(MSBuildToolsPath)\Microsoft.VisualBasic.targets" />, I added in the following lines:

    <PropertyGroup> <PrepareForRunDependsOn>$(PrepareForRunDependsOn);CopyCommonFiles</PrepareForRunDependsOn> </PropertyGroup>

  • 该行下方<Import Project="$(MSBuildToolsPath)\Microsoft.VisualBasic.targets" />,我添加了以下几行:

    <PropertyGroup> <PrepareForRunDependsOn>$(PrepareForRunDependsOn);CopyCommonFiles</PrepareForRunDependsOn> </PropertyGroup>

<Target Name="CopyCommonFiles"> <Copy SourceFiles="@(CommonFiles)" DestinationFolder="$(OutDir)\%(RecursiveDir)" SkipUnchangedFiles="true"/> </Target>

<Target Name="CopyCommonFiles"> <Copy SourceFiles="@(CommonFiles)" DestinationFolder="$(OutDir)\%(RecursiveDir)" SkipUnchangedFiles="true"/> </Target>

This will copy the files from the CommonFilesbuild action into your bin\Debug / bin\Release directories at build time.

这将在CommonFiles构建时将构建操作中的文件复制到 bin\Debug / bin\Release 目录中。

And that's how I did it....

而我就是这样做的......

ANY comments / thoughts are really greatly appreciated )if you think I should have used another way or anything else)....

非常感谢任何评论/想法)如果您认为我应该使用其他方式或其他方式)...

this

这个

回答by Tim S.

You can get the .exe location of your app with System.Reflection.Assembly.GetExecutingAssembly().Location.

您可以使用 .exe 获取应用程序的位置System.Reflection.Assembly.GetExecutingAssembly().Location

string exePath = System.Reflection.Assembly.GetExecutingAssembly().Location;
string exeDir = System.IO.Path.GetDirectoryName(exePath);
DirectoryInfo binDir = System.IO.Directory.GetParent(exeDir);

回答by Christian Sauer

If you have configuration data etc. I would store them in the %Appdata% directory. Putting files which might be changed into the installation directory is not a good Idea and is forbidden since Windows Vista. Configuration data should be stored in the %Appdata% folder, which is a special folder. DO NOT hardcode its path into your program - Users from foreign countries or 32/64bit Windowses will have severe problems.

如果您有配置数据等,我会将它们存储在 %Appdata% 目录中。将可能更改的文件放入安装目录不是一个好主意,并且从 Windows Vista 开始是禁止的。配置数据应存储在 %Appdata% 文件夹中,这是一个特殊文件夹。不要将其路径硬编码到您的程序中 - 来自外国或 32/64 位 Windows 的用户将遇到严重问题。

A good idea how to access the Appdata-Folder can you see here: How to create appdata folder with C#

您可以在此处查看如何访问 Appdata-Folder 的好主意: How to create appdata folder with C#

回答by user2880486

Following code is from http://msdn.microsoft.com/en-us/library/ms229654(v=vs.90).aspx

以下代码来自http://msdn.microsoft.com/en-us/library/ms229654(v=vs.90).aspx

    String strAppDir = Path.GetDirectoryName(
        Assembly.GetExecutingAssembly().GetName().CodeBase);
    String strFullPathToMyFile = Path.Combine(strAppDir, "fileName.txt");

    MessageBox.Show(String.Format("Path to the application is: '{0}'." +
        "Full path to the file in the application folder is: '{1}'",
        strAppDir, strFullPathToMyFile));

回答by Joe

I would do it as follows:

我会这样做:

  • Create a subfolder for the files in your project, e.g. "CommonFiles".

  • Put the config files in this folder. Set their properties to:

    • Build Action = Content

    • Copy to output directory = Copy always (or maybe: Copy if newer)

  • The files will then be copied to bin\Debug\CommonFiles or bin\Release\CommonFiles each time your application is built. You can reference them as:

    Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "CommonFiles\MyFile.Dat");
    
  • 为项目中的文件创建一个子文件夹,例如“CommonFiles”。

  • 将配置文件放在此文件夹中。将它们的属性设置为:

    • 构建操作 = 内容

    • 复制到输出目录 = 始终复制(或者:如果更新则复制)

  • 每次构建应用程序时,这些文件将被复制到 bin\Debug\CommonFiles 或 bin\Release\CommonFiles。您可以将它们引用为:

    Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "CommonFiles\MyFile.Dat");