콘솔 애플리케이션에서 애플리케이션의 경로를 찾으려면 어떻게 하나요?
Windows Forms]1에서는 Application.StartupPath
를 사용하여 현재 경로를 찾을 수 있지만 콘솔 응용 프로그램에서는 이 기능을 사용할 수 없는 것 같습니다.
System.Reflection.Assembly.GetExecutingAssembly()
.Location
1
원하는 것이 디렉터리뿐이라면 System.IO.Path.GetDirectoryName
과 결합합니다.
1민도르 씨의 의견에 따르면: 다음과 같습니다. System.Reflection.Assembly.GetExecutingAssembly().Location
은 실행 중인 어셈블리가 현재 위치한 위치를 반환하며, 실행 중이 아닐 때는 어셈블리가 위치한 위치일 수도 있고 아닐 수도 있습니다. 섀도 복사 어셈블리의 경우 임시 디렉터리의 경로를 가져옵니다. [
System.Reflection.Assembly.GetExecutingAssembly().CodeBase`]4는 어셈블리의 '영구' 경로를 반환합니다.
두 가지 옵션이 있습니다 찾는 고객의 목적에 따라 달라질 수 있는 애플리케이션, 디렉터리이고 선택했다.
// to get the location the assembly is executing from
//(not necessarily where the it normally resides on disk)
// in the case of the using shadow copies, for instance in NUnit tests,
// this will be in a temp directory.
string path = System.Reflection.Assembly.GetExecutingAssembly().Location;
//To get the location the assembly normally resides on disk or the install directory
string path = System.Reflection.Assembly.GetExecutingAssembly().CodeBase;
//once you have the path you get the directory with:
var directory = System.IO.Path.GetDirectoryName(path);
하지만 이는 하라님의 가치가 조금 늦은 것이다.
Environment.GetCommandLineArgs()[0];
또는 더 정확하게는 afaq 그냥 디렉토리에는 경로:
System.IO.Path.GetDirectoryName(Environment.GetCommandLineArgs()[0]);
사람들이 '' 보장되지 않을 수 있다는 지적이 적지 제코먼드리네이리스 반품해야 프로그램 이름이다. 참조 첫 번째 단어 명령줄의 프로그램 이름만 규칙에 따라. 이러한 상태를 윈도용 프로그램을 사용할 수 있지만, 이 기사를 높여줍니까 " 극히 일부 경구 (I am not 모든 것을 혼자) ". # 39, & # 39 spoof& 수 있기 때문에, 하지만 우리는 콘솔 응용 프로그램 ',' 제코먼드리네이리스 대해 얘기하고 있다. 일반적으로 콘솔이군요 앱도 빠르고 더러운. 이 때문에 내 키스 부응합니다 있는 것이다.
여기 내 결과 3 개의 서로 다른 방법 asp.net 웹 어플리케이션에 대한 관심이 많은 분일터다.
protected void Application_Start(object sender, EventArgs e)
{
string p1 = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
string p2 = System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath;
string p3 = this.Server.MapPath("");
Console.WriteLine("p1 = " + p1);
Console.WriteLine("p2 = " + p2);
Console.WriteLine("p3 = " + p3);
}
그 결과
p1 = C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET Files\root\a897dd66\ec73ff95\assembly\dl3\ff65202d\29daade3_5e84cc01
p2 = C:\inetpub\SBSPortal_staging\
p3 = C:\inetpub\SBSPortal_staging
실제로 방영하고, 앱, 첫 번째 솔루션은 웹 어플리케이션을 말해둘꼐요 " C:\inetpub\SBSPortal_staging" 때문에 적절치 않다.
내가 그 위에 90% 가 필요하지만, Uri 반환되었습니다 대신 일반 패스로 for me.
Msdn forum 에서 설명한 후, [어떻게 정상적인 경로를 변환할지 URI 파일 경로?] (http://social.msdn.microsoft.com/Forums/ar/csharplanguage/thread/9341a48b-5c23-4b54-a354-2e21732cbea5), 내가 예전에는 다음과 같습니다.
// Get normal filepath of this assembly's permanent directory
var path = new Uri(
System.IO.Path.GetDirectoryName(
System.Reflection.Assembly.GetExecutingAssembly().CodeBase)
).LocalPath;
이 콘솔 응용 프로그램을 볼 수 있습니다.
System.IO.Directory.GetCurrentDirectory();
출력 (내 로컬 컴퓨터의): >. 2012\projects\imagehandler\getdir\bin\debug c:\users\xxxxxxx\documents\visual 스튜디오
또는 볼 수 있습니다 (there& # 39 에 추가로 백슬래시 귀의하매):
AppDomain.CurrentDomain.BaseDirectory
출력: >. 2012\projects\imagehandler\getdir\bin\debug\ c:\users\xxxxxxx\documents\visual 스튜디오
Net 호환 사용 방법을 찾고 있다면 핵심
System.AppContext.BaseDirectory
이 .NET 프레임워크 4.6, 닷넷 (.net) 코어 1.0 (및 닷넷 (.net) 기반 표준 1.3) 에 처음 도입되었다. 참조: [아프콘테스트롬바스트리스토리 속성] [1].
이 페이지 에 따르면,
>. 이것은 .NET 에서는 기본 대한 교체품을 아프도메인스커랑도메인스바스트리스토리 핵심
[1]: 보기 = netframework-4.7.1 https://docs.microsoft.com/en-us/dotnet/api/system.appcontext.basedirectory?
다음 줄을 너회가 부여하느뇨 애플리케이션과는 경로:
var applicationPath = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName)
위 솔루션이므로 정상적으로 상황은 다음과 같습니다.
내 말은, 왜안돼요 p / invoke 방법?
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
public class AppInfo
{
[DllImport("kernel32.dll", CharSet = CharSet.Auto, ExactSpelling = false)]
private static extern int GetModuleFileName(HandleRef hModule, StringBuilder buffer, int length);
private static HandleRef NullHandleRef = new HandleRef(null, IntPtr.Zero);
public static string StartupPath
{
get
{
StringBuilder stringBuilder = new StringBuilder(260);
GetModuleFileName(NullHandleRef, stringBuilder, stringBuilder.Capacity);
return Path.GetDirectoryName(stringBuilder.ToString());
}
}
}
그냥 사용하는 것과 같은 아프리카션리스트라토퍼스:
Console.WriteLine("The path to this executable is: " + AppInfo.StartupPath + "\\" + System.Diagnostics.Process.GetCurrentProcess().ProcessName + ".exe");
'아서 블리스게텐트리아스럼블리 콜로카션 아서 블리스게테스쿠팅아스럼블리 콜로카션' () '또는' ()
함께 사용하여 () '만' 시스템드리오파트리짓디레스토리나미 afaq 디렉터리입니다.
이 경로를 통해 '게텐트리아스럼블리 ()' 와 '게테스쿠팅아스럼블리 있음에도 불구하고 대부분의 경우에 따라 다를 수 있습니다 ()' 의 디렉토리에는 같아집니다.
() '와' 게텐트리아스럼블리 빈틈없어야 반환할 수 있다는 사실을 알고 이 경우 'null' 는 입력입니다 모듈에서는 비관리 (ie c++컴파일러는 또는 VB6 실행가능파일). 이러한 경우는 '에서' 제모두리피렌임 Win32 API 를 사용할 수 있습니다.
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
public static extern int GetModuleFileName(HandleRef hModule, StringBuilder buffer, int length);
이러한 방법을 사용하여 같은 특별한 사유가 없는 작업하십시오 기호식 https://partner. microsoft. exe, 그들은 실제 위치를 반환되므로 https://partner. 아닌 exe.
[케리풀프로스시마겐임] [1] 해결하기 위해 사용할 수 있도록 하는.
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Diagnostics;
internal static class NativeMethods
{
[DllImport("kernel32.dll", SetLastError = true)]
internal static extern bool QueryFullProcessImageName([In]IntPtr hProcess, [In]int dwFlags, [Out]StringBuilder lpExeName, ref int lpdwSize);
[DllImport("kernel32.dll", SetLastError = true)]
internal static extern IntPtr OpenProcess(
UInt32 dwDesiredAccess,
[MarshalAs(UnmanagedType.Bool)]
Boolean bInheritHandle,
Int32 dwProcessId
);
}
public static class utils
{
private const UInt32 PROCESS_QUERY_INFORMATION = 0x400;
private const UInt32 PROCESS_VM_READ = 0x010;
public static string getfolder()
{
Int32 pid = Process.GetCurrentProcess().Id;
int capacity = 2000;
StringBuilder sb = new StringBuilder(capacity);
IntPtr proc;
if ((proc = NativeMethods.OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, false, pid)) == IntPtr.Zero)
return "";
NativeMethods.QueryFullProcessImageName(proc, 0, sb, ref capacity);
string fullPath = sb.ToString(0, capacity);
return Path.GetDirectoryName(fullPath) + @"\";
}
}
[1]: 이아스파스 https://msdn.microsoft.com/en-us/library/ms684919 (v = vs. 85)