2012-12-27 32 views
0

好吧,我的問題是,當我嘗試訪問文件,而路徑的文件名是從DataTable它只是無法找到該文件。C# - 從DataTable的路徑字符串的一部分時無法找到文件

我已經測試了它,當我從一個文本文件解析的文件名或字符串中的硬編碼只是......和ofcourse這項工作> _ <

只是不明白其中的差異是,當我從字符串的文件名數據表。

其打造看起來像這樣的字符串:

C:\服務器\ SYSTEM/somefile.dat

下面是代碼:

string accountConnectionString = ConfigurationManager.ConnectionStrings["connstring"].ConnectionString; 

    public Form1() 
    { 
     InitializeComponent(); 
    } 

    private void button1_Click(object sender, EventArgs e) 
    { 
     LoadFileChecks(); 
    } 

    public SqlConnection GetAccountConnection() 
    { 
     SqlConnection connection = new SqlConnection(accountConnectionString); 
     connection.Open(); 
     return connection; 
    } 


    public DataTable getFilecheck() 
    { 
     using (var con = GetAccountConnection()) 
     { 
      SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM tFilecheck", con); 
      DataTable ds = new DataTable("Filecheck"); 
      da.Fill(ds); 
      con.Close(); 
      return ds; 
     } 
    } 

    public void LoadFileChecks() 
    { 
     DataTable table = getFilecheck(); 
     string localPath = Application.StartupPath; 

     foreach (DataRow row in table.Rows) 
     { 
      string line = row["sFilename"].ToString(); 

      string FilePath = localPath + "\\" + line; 
      if (!File.Exists(FilePath)) 
      { 
       MessageBox.Show("File not found"); 
       continue; 
      } 
     } 

    } 
+0

不用手動試圖串連的路徑和文件名,並Munge時間雙斜槓應該改變路徑服務器路徑,查找的方法[Path.Combine(HTTP:// MSDN .microsoft.com/en-us/library/fyy7a5kt(v = vs.110).aspx),它爲您完成繁重的工作。 –

+0

確定嘗試過,字符串看起來像現在:「C:\\ Server \\ system \\ somefile.dat」但仍找不到文件:< – Saschanski

回答

0

首先,Application.StartupPath是取決於你如何部署應用程序的exe。

string localPath = Application.StartupPath; 

將當前執行路徑時,調試(如項目\ BIN \調試)

其次,你不需要逃避與\\

樣品每一個反斜槓,而不是..

string path = "C:\\Server\\system"; 

嘗試逃避串@

string path = @"C:\Server\system"; 

然後Path.Combine與文件名

string fileName = row["sFilename"].ToString(); 
string filePath = Path.Combine(path, fileName); 
//Path.Combine(@"C:\Server\system", "somefile.dat"); 
+0

本地路徑是「C:\\服務器」,它得到「系統\ somefile.dat「從數據表中。它構建的字符串是「C:\\ Server \\ system \\ somefile.dat」,對我來說這看起來很好,但它不會工作......只有當我從數據庫獲取文件路徑時纔會發生這種情況> _ <從文本文件或硬編碼工作得很好.. – Saschanski

0

這是一個.NET Web應用程序?如果是,你使用

path = Server.MapPath(path); 
+0

不管這是一個winforms,它建立了正確的字符串..只是無法看到該文件 – Saschanski

相關問題