C#错误保存Excel文件

我对C#很陌生,而且我正在尝试很多,我试图让我的程序更友好一点,这就是问题的出发点。 起初,excelfile的位置是在一个公共的静态string,我没有任何问题。 我改变了这个:

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; } 

和我使用的button,所以用户可以给我一个位置的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文件是没有问题的,我的程序find并处理它,当且仅当用户通过使用“浏览”button来改变位置时,我从Windows得到一个消息,说明已经有一个名称为excel的文件,如果我想replace它,如果我点击该消息,我的代码给出的错误尝试保存Excel文件的行

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

xlWorkbook.Save()给我这个错误:

发生System.Runtime.InteropServices.COMException
HResult = 0x800A03EC消息= Verjaardagen.xlsx无法保存,因为它是只读的。

我不知道为什么我没有得到与默认位置的错误,而如果使用我的button给我的同一个位置,我得到一个错误。

有谁知道我在做什么错?

提前致谢

所以问题在于,只有在您尝试通过but_Browse_Click后写入文件时才能读取文件。 你正在closuresStreamReader? 尝试使用

reader.close();

在but_Browse_Click中。

也许更好的方法是:

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

这完成后自动closures。