什么是.NET相当于Java的System.getProperty(" user.dir指定")?System、Java、NET、getProperty

2023-09-05 23:41:03 作者:﹏゛低吟╮

我试图让我的单元测试文件,该文件是在我的项目文件夹中的完整路径。 我试图用

  Directory.GetCurrentDirectory();
 

但它返回我的测试中,我希望这个项目(或解决方案)的目录,而不必硬code它在那里运行的目录下。然后,我可以追加文件名的最后一部分。类似的东西,以

  System.getProperty(user.dir来)
 

在Java

解决方案

  Path.GetDirectoryName(Assembly.GetExecutingAssembly()。地点)
 
什么是.NET 什么是.NET Framework 什么是.NET Core 上

将让你在运行单元测试DLL本身。路径

为了访问一个文件中的一个项目子文件夹,做最简单的事情就是标记相关文件,生成操作=内容复制到输出目录=复制如果新。如果你这样做,那么他们将被复制到正在运行的组件文件夹下的文件夹相对只要您构建项目。然后,您可以计算的物理路径相对于正在运行的程序集。

例如:

您已经位于℃的文本文件;项目的根> \ TESTDATA \ DATA1.TXT 当您构建在调试模式下的项目,将被复制到<项目的根> \斌\调试\ TESTDATA \ DATA1.TXT 在code的物理路径将是 Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly()位置),TESTDATA \ DATA1.TXT)

I am trying to get the full path of a file in my unit test which is in a folder in my project. i tried using

Directory.GetCurrentDirectory();

but that returns the directory which my tests are running in. I want the directory of the project (or solution) without having to hard-code it in there. Then I can append the last part of the filename. Something similar to

System.getProperty("user.dir")

in java

解决方案

Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)

will get you the path of the running unit test DLL itself.

In order to access a file in a project subfolder, the simplest thing to do is mark the relevant files as Build Action = Content and Copy to Output Directory = Copy if newer. If you do that, then they will be copied to relative folders underneath the running assembly folder whenever you build the project. You can then calculate the physical path relative to the running assembly.

For example:

You have a text file located at <project root>\TestData\Data1.txt. When you build the project in Debug mode, it will be copied to <project root>\bin\Debug\TestData\Data1.txt. The physical path in your code will be Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "TestData\Data1.txt").
 
精彩推荐