사용자 지정 MSBuild 작업을 만들 때 C # 코드에서 현재 프로젝트 디렉토리를 얻는 방법은 무엇입니까?
경로가 하드 코딩 된 외부 프로그램을 실행하는 대신 현재 Project Dir을 얻고 싶습니다. 사용자 지정 작업의 프로세스를 사용하여 외부 프로그램을 호출하고 있습니다.
어떻게해야합니까? AppDomain.CurrentDomain.BaseDirectory는 VS 2008의 위치를 알려줍니다.
이 두 가지 방법 중 하나를 시도 할 수 있습니다.
string startupPath = System.IO.Directory.GetCurrentDirectory();
string startupPath = Environment.CurrentDirectory;
말해봐, 어느 쪽이 더 나아 보인다
using System;
using System.IO;
// This will get the current WORKING directory (i.e. \bin\Debug)
string workingDirectory = Environment.CurrentDirectory;
// or: Directory.GetCurrentDirectory() gives the same result
// This will get the current PROJECT directory
string projectDirectory = Directory.GetParent(workingDirectory).Parent.FullName;
프로젝트가 IIS Express에서 실행중인 경우 프로젝트가 Environment.CurrentDirectory
있는 위치가 아니라 IIS Express가있는 위치 (기본 경로는 C : \ Program Files (x86) \ IIS Express )를 가리킬 수 있습니다.
이것은 아마도 다양한 종류의 프로젝트에 가장 적합한 디렉토리 경로 일 것입니다.
AppDomain.CurrentDomain.BaseDirectory
이것이 MSDN 정의입니다.
어셈블리 확인자가 어셈블리를 검사하는 데 사용하는 기본 디렉터리를 가져옵니다.
또한 현재 실행중인 디렉토리에서 두 레벨을 탐색하여 프로젝트 디렉토리를 제공합니다 (모든 빌드에 대해 프로젝트 디렉토리를 반환하지는 않지만 가장 일반적입니다).
System.IO.Path.GetFullPath(@"..\..\")
물론 이것을 일종의 유효성 검사 / 오류 처리 논리 안에 포함하고 싶을 것입니다.
솔루션이있는 디렉토리가 무엇인지 아는 경우 다음을 수행해야합니다.
var parent = Directory.GetParent(Directory.GetCurrentDirectory()).Parent;
if (parent != null)
{
var directoryInfo = parent.Parent;
string startDirectory = null;
if (directoryInfo != null)
{
startDirectory = directoryInfo.FullName;
}
if (startDirectory != null)
{ /*Do whatever you want "startDirectory" variable*/}
}
GetCurrrentDirectory()
method 만 사용 하면 디버깅 또는 릴리스 여부에 관계없이 빌드 폴더가 생성됩니다. 도움이 되었기를 바랍니다. 유효성 검사를 잊어 버린 경우 다음과 같습니다.
var startDirectory = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.Parent.FullName;
나도 이것을 찾고 있었다. HWC를 실행하는 프로젝트가 있는데 웹 사이트를 앱 트리 외부에 유지하고 싶지만 디버그 (또는 릴리스) 디렉토리에 유지하고 싶지 않습니다. FWIW에서 허용되는 솔루션 (및이 솔루션)은 실행 파일이 실행중인 디렉토리 만 식별합니다.
그 디렉토리를 찾기 위해
string startupPath = System.IO.Path.GetFullPath(".\\").
이 작업을 수행하는 다른 방법
string startupPath = System.IO.Directory.GetParent(@"./").FullName;
bin 폴더의 경로를 얻으려면
string startupPath = System.IO.Directory.GetParent(@"../").FullName;
아마도 더 좋은 방법이있을 것입니다 =)
또 다른 불완전한 해결책 (그러나 아마도 다른 것보다 약간 더 완벽에 가깝습니다) :
protected static string GetSolutionFSPath() {
return System.IO.Directory.GetParent(System.IO.Directory.GetCurrentDirectory()).Parent.Parent.FullName;
}
protected static string GetProjectFSPath() {
return String.Format("{0}\\{1}", GetSolutionFSPath(), System.Reflection.Assembly.GetExecutingAssembly().GetName().Name);
}
이 버전은 현재 프로젝트가 솔루션 용이 아니더라도 현재 프로젝트의 폴더를 반환합니다 Startup Project
.
이것의 첫 번째 결함은 모든 오류 검사를 건너 뛰었다는 것입니다. 그것은 쉽게 고칠 수 있지만 드라이브의 루트 디렉토리에 프로젝트를 저장하거나 경로의 접합을 사용하고 (이 접합은 솔루션 폴더의 후손) 문제가 될 수 있으므로이 시나리오는 거의 없습니다 . 어쨌든 Visual Studio가 이러한 설정 중 하나를 처리 할 수 있는지 확실하지 않습니다.
발생할 수있는 또 다른 문제는 프로젝트 이름이 프로젝트 의 폴더 이름과 일치 해야 프로젝트를 찾을 수 있다는 것입니다.
또 다른 문제는 프로젝트가 솔루션 폴더 안에 있어야한다는 것입니다. 이것은 일반적으로 문제가되지 않지만 Add Existing Project to Solution
프로젝트를 솔루션에 추가하는 옵션을 사용한 경우 솔루션 구성 방식이 아닐 수 있습니다.
마지막으로, 응용 프로그램에서 작업 디렉토리를 수정하는 경우이 값은 현재 작업 디렉토리를 기준으로 결정되므로이 값을 저장하기 전에 저장해야합니다.
물론 이것은 프로젝트 속성 대화 상자에서 프로젝트 Build
-> Output path
또는 Debug
-> Working directory
옵션 의 기본값을 변경해서는 안된다는 것을 의미합니다 .
이 간단한 시도
HttpContext.Current.Server.MapPath("~/FolderName/");
대답을 도출하기 위해 공개 문자열의 미국에 관한 첫 번째 답변을 마무리 한 후에는 원하는 결과를 얻기 위해 레지스트리에서 값을 읽을 수 있다고 생각했습니다. 결과적으로 그 경로는 더 짧았습니다.
먼저 레지스트리 작업을 수행 할 수 있도록 Microsoft.Win32 네임 스페이스를 포함해야합니다.
using Microsoft.Win32; // required for reading and / or writing the registry
주요 코드는 다음과 같습니다.
RegistryKey Projects_Key = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\Microsoft\VisualStudio\9.0", false);
string DirProject = (string)Projects_Key.GetValue(@"DefaultNewProjectLocation");
이 답변에 대한 참고 사항 :
I am using Visual Studio 2008 Professional Edition. If you are using another version, (i.e. 2003, 2005, 2010; etc.), then you mayt have to modify the 'version' part of the SubKey string (i.e. 8.0, 7.0; etc.).
If you use one of my answers, and if it is not too much to ask, then I would like to know which of my methods you used and why. Good luck.
- dm
I had a similar situation, and after fruitless Googles, I declared a public string, which mods a string value of the debug / release path to get the project path. A benefit of using this method is that since it uses the currect project's directory, it matters not if you are working from a debug directory or a release directory:
public string DirProject()
{
string DirDebug = System.IO.Directory.GetCurrentDirectory();
string DirProject = DirDebug;
for (int counter_slash = 0; counter_slash < 4; counter_slash++)
{
DirProject = DirProject.Substring(0, DirProject.LastIndexOf(@"\"));
}
return DirProject;
}
You would then be able to call it whenever you want, using only one line:
string MyProjectDir = DirProject();
This should work in most cases.
Use this to get the Project directory (worked for me):
string projectPath =
Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName;
Based on Gucu112's answer, but for .NET Core Console/Window application, it should be:
string projectDir =
Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"..\..\.."));
I'm using this in a xUnit project for a .NET Core Window Application.
I have used following solution to get the job done:
string projectDir =
Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"..\.."));
Try:
var pathRegex = new Regex(@"\\bin(\\x86|\\x64)?\\(Debug|Release)$", RegexOptions.Compiled);
var directory = pathRegex.Replace(Directory.GetCurrentDirectory(), String.Empty);
This is solution different from the others does also take into account possible x86 or x64 build.
This solution works well for me, on Develop and also on TEST and PROD servers with ASP.NET MVC5 via C#:
var projectDir = Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory);
If you need project directory in project configuration file use:
$(ProjectDir)
The best solution
string PjFolder1 =
Directory.GetParent(AppDomain.CurrentDomain.BaseDirectory).
Parent.Parent.FullName;
Other solution
string pjFolder2 = Path.GetDirectoryName(Path.GetDirectoryName(Path.GetDirectoryName(
System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase)));
Test it, AppDomain.CurrentDomain.BaseDirectory worked for me on past project, now I get debug folder .... the selected GOOD answer just NOT WORK!.
//Project DEBUG folder, but STILL PROJECT FOLDER
string pjDebugFolder = AppDomain.CurrentDomain.BaseDirectory;
//Visual studio folder, NOT PROJECT FOLDER
//This solutions just not work
string vsFolder = Directory.GetCurrentDirectory();
string vsFolder2 = Environment.CurrentDirectory;
string vsFolder3 = Path.GetFullPath(".\\");
//Current PROJECT FOLDER
string ProjectFolder =
//Get Debug Folder object from BaseDirectory ( the same with end slash)
Directory.GetParent(pjDebugFolder).
Parent.//Bin Folder object
Parent. //Project Folder object
FullName;//Project Folder complete path
If you really want to ensure you get the source project directory, no matter what the bin output path is set to:
Add a pre-build event command line (Visual Studio: Project properties -> Build Events):
echo $(MSBuildProjectDirectory) > $(MSBuildProjectDirectory)\Resources\ProjectDirectory.txt
Add the
ProjectDirectory.txt
file to the Resources.resx of the project (If it doesn't exist yet, right click project -> Add new item -> Resources file)- Access from code with
Resources.ProjectDirectory
.
using System;
using System.IO;
// Get the current directory and make it a DirectoryInfo object.
// Do not use Environment.CurrentDirectory, vistual studio
// and visual studio code will return different result:
// Visual studio will return @"projectDir\bin\Release\netcoreapp2.0\", yet
// vs code will return @"projectDir\"
var currentDirectory = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory);
// On windows, the current directory is the compiled binary sits,
// so string like @"bin\Release\netcoreapp2.0\" will follow the project directory.
// Hense, the project directory is the great grand-father of the current directory.
string projectDirectory = currentDirectory.Parent.Parent.Parent.FullName;
This works on VS2017 w/ SDK Core MSBuild configurations.
You need to NuGet in the EnvDTE / EnvDTE80 packages.
Do not use COM or interop. anything.... garbage!!
internal class Program {
private static readonly DTE2 _dte2;
// Static Constructor
static Program() {
_dte2 = (DTE2)Marshal.GetActiveObject("VisualStudio.DTE.15.0");
}
private static void FindProjectsIn(ProjectItem item, List<Project> results) {
if (item.Object is Project) {
var proj = (Project) item.Object;
if (new Guid(proj.Kind) != new Guid(Constants.vsProjectItemKindPhysicalFolder))
results.Add((Project) item.Object);
else
foreach (ProjectItem innerItem in proj.ProjectItems)
FindProjectsIn(innerItem, results);
}
if (item.ProjectItems != null)
foreach (ProjectItem innerItem in item.ProjectItems)
FindProjectsIn(innerItem, results);
}
private static void FindProjectsIn(UIHierarchyItem item, List<Project> results) {
if (item.Object is Project) {
var proj = (Project) item.Object;
if (new Guid(proj.Kind) != new Guid(Constants.vsProjectItemKindPhysicalFolder))
results.Add((Project) item.Object);
else
foreach (ProjectItem innerItem in proj.ProjectItems)
FindProjectsIn(innerItem, results);
}
foreach (UIHierarchyItem innerItem in item.UIHierarchyItems)
FindProjectsIn(innerItem, results);
}
private static IEnumerable<Project> GetEnvDTEProjectsInSolution() {
var ret = new List<Project>();
var hierarchy = _dte2.ToolWindows.SolutionExplorer;
foreach (UIHierarchyItem innerItem in hierarchy.UIHierarchyItems)
FindProjectsIn(innerItem, ret);
return ret;
}
private static void Main() {
var projects = GetEnvDTEProjectsInSolution();
var solutiondir = Path.GetDirectoryName(_dte2.Solution.FullName);
// TODO
...
var project = projects.FirstOrDefault(p => p.Name == <current project>);
Console.WriteLine(project.FullName);
}
}
Directory.GetParent(Directory.GetCurrentDirectory()).Parent.Parent.Parent.Parent.FullName
Will give you the project directory.
'IT박스' 카테고리의 다른 글
APK가 서명되었거나 "디버그 빌드"인지 확인하는 방법 (0) | 2020.07.22 |
---|---|
div를 세로로 가운데에 배치하는 방법은 무엇입니까? (0) | 2020.07.22 |
플레이스 홀더 Mixin SCSS / CSS (0) | 2020.07.22 |
파이썬 구문에 새로운 문장을 추가 할 수 있습니까? (0) | 2020.07.21 |
GetLastError ()에서 반환 한 오류 코드에서 오류 메시지를 얻는 방법은 무엇입니까? (0) | 2020.07.21 |