2011-03-15 58 views
0

我的代碼訪問位於我的項目目錄中「Conf」目錄中的文件。我使用類似下面的絕對路徑當前打開文件:File.ReadAllLines方法的相對路徑

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

我thinikng如果有可能使用像

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

的相對路徑,但它不工作;如預期的那樣拋出異常。我沒有檢查MSDN(下面的鏈接),但似乎「ReadAllLines()」方法不接受相對路徑。

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

任何想法,我怎麼能使用相對路徑,而不是使用絕對路徑?

感謝, 拉胡爾

回答

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

如前所述MSDN中不能使用相對路徑,但你也許能夠爲使用Environment.CurrentDirectorySystem.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...