2016-12-08 140 views
-4

請找到更新的代碼。在這裏我試圖打開一個存在的文件。這是代碼片段。 sample.txt是獲取完整的文件路徑。我手動使用該路徑並能夠打開文本文件。但通過代碼我無法打開它。無法使用C#中的System.IO.File.OpenText(文件路徑)打開文件。

private void button1_Click(object sender, EventArgs e) 
     { 
      //to search for a file in folder 
      String name_of_file = textBox1.Text; 
      String search_file = @"D:\Shreyas\" + name_of_file + ".txt"; 
      System.IO.File.WriteAllText("D:\\Shreyas\\sample.txt", search_file); 

      //search and open the file 
      if(System.IO.File.Exists(search_file)) 
      { 
       MessageBox.Show("File Found!!"); 

       System.IO.File.OpenText(search_file); 
      } 

      else 
      { 
       MessageBox.Show("File Doesn't Exist!!"); 

      } 
     } 
+0

'd:\\\\ Shreyas \\\\ shreyas.txt '不是一個有效的路徑。 – Equalsk

+0

試試'「D:\\ Shreyas \\ shreyas.txt」'而不是'「D:\\\\ Shreyas \\\\ shreyas.txt」' – Alexei

+2

您是否能夠找到該文件並且不能打開它,或者你能不能找到它?將代碼片段轉儲到SO問題中並不意味着這是一個問題,請告訴我們您嘗試了什麼,以及您需要什麼幫助。 –

回答

0

編輯後的版本:

private void button1_Click(object sender, EventArgs e) 
    { 
     //to search for a file in folder 
     String name_of_file = "Test"; 
     String search_file = @"C:\Users\User\Desktop\" + name_of_file + ".txt"; 
     //System.IO.File.WriteAllText("D:\\Shreyas\\sample.txt", search_file); 

     //search and open the file 
     if (System.IO.File.Exists(search_file)) 
     { 
      string tmp = System.IO.File.OpenText(@"C:\Users\User\Desktop\" + name_of_file + ".txt").ReadLine(); 
      System.IO.File.WriteAllText(@"C:\Users\User\Desktop\Test_Write.txt", tmp); 
     } 

     else 
     { 
      Debug.WriteLine("Doesnt Exists"); 

     } 
    } 

這將讀取和寫入文件到另一個文件。

嘗試:@"D:\Shreyas\shreyas.txt"

在字符串的開頭@符號告訴C#,這是他需要使用並準確地將其格式化爲你:)

編輯路徑:

剛看到你的評論。讀它使用:

string tmpString = System.IO.File.OpenText(@"C:\Users\User\Desktop\" + name_of_file + ".txt").ReadLine());

另外,不要忘記處置您的FileReader。如果你不這樣做,你將無法編輯你的文件,而你的應用程序running.`

要打開文本文件,嘗試System.Diagnostics.Process.Start(search_file);

+0

感謝您的解決方案。但該文件仍未打開所有更改。 – user1967685

+0

@ user1967685當您在撰寫評論時,我編輯了我的解決方案:D我添加了如何將文件文本加載到字符串中。 – Cataklysim

+0

不幸運!仍然無法打開文本文件。我不知道y這個基本功能不起作用 – user1967685

0

路徑始終是這樣的:

Drive:\PATH\TO\SOME\FOLDER 

,你的路徑是:

string.Format("{0}{1}{2}{1}{3}", "D:", Path.DirectorySeparatorChar, "Folder", "file.txt"); 

Drive:\\PATH\\TO\\SOME\\FOLDER 

您可以輕鬆地改變串入做這方面的工作

或僅僅是:

Path.Combine("D:","Folder", "file.txt"); 
0

你應該嘗試:

string path = @"D:\Shreyas\shreyas.txt"; 
System.IO.File.OpenText(path); 
+0

不幸運!它仍然沒有打開 – user1967685