2014-11-09 97 views
0

我打開了一個目錄,並且讀取了該目錄中的一些文件,並做了一些更改,現在我想用相同的文件名保存更改F:\ BI \ Out \並保留原始文件。 當我添加這兩行 var outFilePath = @「F:\ BI \ Out \」+ Path.GetFileName(file); File.WriteAllText(outFilePath,text); 我能夠將文件保存在新文件夾\ Out, 下,但是當我打開它們時,我發現只有一個文件被正確更改,所有其他文件中的舊文字被空白空間替換,而不是新文字。 誰能幫我謝謝我做了一些更改後,如何在某個目錄下的某個目錄下保存某些文件

string text = ""; 
    string[] files; 

    private void Form1_Load(object sender, EventArgs e) 
    { 

     try 
     { 
      files = Directory.GetFiles(@"F:\BI\In\", "*.*", SearchOption.AllDirectories); 
     } 
     catch (IOException ex) 
     { 
      MessageBox.Show(ex.Message); 
      this.Close(); 
     } 
    } 

    private void btnUpdate_Click(object sender, EventArgs e) 
    { 
     if (txtEtlPath.Text == "") 
     { 
      MessageBox.Show("Please Enter path"); 
      txtEtlPath.Focus(); 
     } 

     else 
     { 

      foreach (string file in files) 
      { 
       if (System.IO.File.Exists(file)) 
       { 
        text = File.ReadAllText(file); 
        text = text.Replace("Company_Address", txtCompanyAddress.Text + "_BI"); 
        text = text.Replace("Company_Name", txtCompanyName.Text.Trim() + "_BIDW"); 
        text = text.Replace("C:\\BIfolder",cboDrive.Text + txtEtlPath.Text.Trim()); 
        var outFilePath = @"F:\BI\Out\" + Path.GetFileName(file); 
        File.WriteAllText(outFilePath, text); 
       } 
+0

搜索是你的朋友,無論是在谷歌或Stackoverflow。[**'Directory.CreateDirectory' **方法](http://msdn.microsoft.com/en-us/library/system.io.directory.createdirectory%28v=vs。 110%29.aspx)和[**'如何:寫入文本文件**](http://msdn.microsoft.com/en-us/library/8bh11f1k.aspx)? – Prix 2014-11-09 01:28:00

回答

0

在您的foreach()循環:

如果你想要的文件的子文件夾結構中發現,做一個替代的文件路徑:

var outFilePath = file.Replace(@"F:\BI\In\", @"F:\BI\Out\"); 

你將需要創建子文件夾,然後才能寫入更改的文件:

new FileInfo(outFilePath)).Directory.Create(); 

如果你不希望子文件夾,你可以直接寫入頂層文件夾:

var outFilePath = @"F:\BI\Out\" + Path.GetFileName(file); 

寫作很簡單,只需記住有一個可選的編碼參數:

File.WriteAllText(outFilePath, text); 
+0

感謝您對此的支持:) – Mohamed 2014-11-09 16:22:25

+0

我能夠將文件保存在新文件夾\ Out下,但是當我打開它們時,我發現只有一個文件被正確更改,其他所有文件的舊文字都被替換爲空白空間不是由新單詞 – Mohamed 2014-11-09 17:33:27

+0

我看不到任何發佈會導致這種情況,在每個文本上放置斷點。替換行,將鼠標懸停在文本和文本框變量上,以查看已讀和什麼每個替換正在改變。 – WhoIsRich 2014-11-10 01:17:05

相關問題