2011-03-15 2 views
0

내 코드는 내 프로젝트 디렉토리의 "Conf"디렉토리에있는 파일에 액세스합니다. 나는 현재 아래와 같은 절대 경로를 사용하여 파일을 여는 오전 :File.ReadAllLines 메서드의 상대 경로

File.ReadAllLines("C:\project name\Conf\filename"); 

File.ReadAllLines("/Conf/filename"); 

같은 상대 경로를 사용하는 것이 가능하다면 나는 thinikng했다 그러나 그것은 작동하지 않습니다; 예상대로 예외가 throw됩니다. 나는 MSDN (아래 링크)을 확인했지만 "ReadAllLines()"메서드는 상대 경로를 허용하지 않는 것 같습니다.

http://msdn.microsoft.com/en-us/library/s2tte0y1.aspx

어떤 생각

는 어떻게 상대 경로 대신 절대 경로를 사용하여 사용할 수 있습니까?

감사합니다, 당신은 상대 경로를 사용할 수 없습니다 MSDN에 라훌 언급 한 바와 같이

답변

1

이 그 일을 내 마음에 드는 방법이다.

  1. 파일을 포함 리소스로 설정하십시오.

    /// <summary> 
        /// This class must be in the same folder as the embedded resource 
        /// </summary> 
    public class GetResources 
    {  
        private static readonly Type _type = typeof(GetResources); 
    
        public static string Get(string fileName) 
        { 
         using (var stream = 
         _type.Assembly.GetManifestResourceStream 
         (_type.Namespace + "." + fileName)) 
         { 
          if (stream != null) 
           using (var reader = new StreamReader(stream)) 
           { 
            return reader.ReadToEnd(); 
           } 
         } 
         throw new FileNotFoundException(fileName); 
        } 
    } 
    
0

는, 그러나 당신이 사용할 수 있습니다 중 하나 Environment.CurrentDirectory 또는 System.Reflection.Assembly.GetExecutingAssembly().Location

0

다음 사용 일을 간단하게하려면 :

string current_path = System.IO.Path.GetDirectoryName(Application.ExecutablePath); 

string[] lines_from_file = System.IO.File.ReadAllLines(current_path + "/Conf/filename"); 

...additional black magic here...