2017-10-06 41 views
1

我是C#的新手,我正在嘗試很多,我試圖讓我的程序更友好一些,這就是問題的出發點。 首先,excelfile的位置是一個公共靜態字符串,我沒有問題。我把它改成這樣:C#錯誤保存Excel文件

public string Excellocation() 

    { 
     string xlLocation; 
     if (but_Browse.Text == "Zoek Excel") 
     { 

      xlLocation = @"E:\Levi\Documents\Verjaardagen.xlsx"; 
     } 
     else //Only if I get into this part of my code I get the error 
     { 
      xlLocation = but_Browse.Text; 
     } 
     return xlLocation; 
    } 

而且我使用,使用戶可以給我一個位置,以Excel文件中的按鈕:

private void but_Browse_Click(object sender, EventArgs e) 
    { 

     var FD = new System.Windows.Forms.OpenFileDialog(); 
     if (FD.ShowDialog() == System.Windows.Forms.DialogResult.OK) 
     { 
      string fileToOpen = FD.FileName; 

      System.IO.FileInfo File = new System.IO.FileInfo(FD.FileName); 

      //OR 

      System.IO.StreamReader reader = new System.IO.StreamReader(fileToOpen); 
      //etc 
      but_Browse.Text = fileToOpen; 
      this.but_Browse.AutoSize = true; 
      But_Import.Visible = true; 
     } 

    } 

讀取Excel的文件是沒有問題的,我的程序找到並處理它,當且僅當用戶通過使用「瀏覽按鈕」更改位置時,我從Windows收到一條消息,說已經有一個帶有該名稱的Excel文件,如果我想替換它,如果我點擊該消息,我的代碼給出了一條錯誤消息,試圖保存excel文件

  xlWorkbook.Save(); 
      xlWorkbook.Close(true); 
      xlApp.Quit(); 
      System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp); 

xlWorkbook.Save()給了我這個錯誤:

System.Runtime.InteropServices.COMException occurred
HResult=0x800A03EC Message=Verjaardagen.xlsx can not be saved, because it's read-only.

我不知道爲什麼我不使用默認的位置得到一個錯誤,當我做,如果用我的按鈕,讓我得到一個錯誤相同的位置。

有誰知道我在做什麼錯?

在此先感謝

+0

如果您將代碼修改爲:'xlLocation = but_Browse.Text; MessageBox.Show(xlLocation);'這是否給你任何線索? –

+0

這個messagebox給了我這個: E:\ Levi \ Documents \ Verjaardagen.xlsx 那應該是對的吧? –

+0

這是否與你的'StreamReader'有關,當你試圖保存它時是否打開了該文件? –

回答

0

所以問題是,該文件只當您試圖通過but_Browse_Click會後寫信給它看?你正在關閉StreamReader?在嘗試使用but_Browse_Click

reader.close();

也許一個更好的方式是:

using (StreamReader reader = new StreamReader(fileToOpen)) { //all code involving the reader in here }

這在完成後自動關閉。