When I use c# to read a excel which I use excel to open it, there is a error The process cannot access the file 'xxxx' because it is being used by another process.
Is there any way to do this, I don't wan't open it for every time.
When I use c# to read a excel which I use excel to open it, there is a error The process cannot access the file 'xxxx' because it is being used by another process.
Is there any way to do this, I don't wan't open it for every time.
I'm not sure how you're trying to read the xlsx file, so it might not be possible using the library or tool that you are currently using.
It is possible to open the file stream for reading while Excel has the file open. However, you should be aware that it is also inherently dangerous. The process reading the excel file expects to be reading a consistent view of the file. If Excel decides to write to that same file while it is being read, then it is almost assured that the reading process will fail in some catastrophic way. Since an .xlsx file is just a zip file, the most likely result will be a failure in accessing or decompressing one of the .xlsx entries.
Here is an example of how you can do this using a library I maintain: Sylvan.Data.Excel.
var file = "myfile.xlsx";
// DANGEROUS: open it for reading, but allow other processes to write to it at the same time.
var stream = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
// gets the workbook type from the filename extension
var type = ExcelDataReader.GetWorkbookType(file);
// create the data reader
var reader = ExcelDataReader.Create(stream, type);
// loop over rows
while (reader.Read())
{
// write out the data in the row
Console.WriteLine("Row: " + reader.RowNumber);
for (int i = 0; i < reader.RowFieldCount; i++)
{
Console.WriteLine(reader.GetString(i));
}
Console.WriteLine();
}