I am trying to read multiple cells from a range out of an .xslx-file. I get the error that a process can not access the file because it is being used by another process.
First I had the problem that has been described in this topic: (unable to cast COM object of type 'microsoft.Office.Interop.Excel.ApplicationClass' to 'microsoft.Office.Interop.Excel.Application'"). I fixed that problem by running the repair for MSOffice Professional Plus. After I have done that, the errors I am mentioning after the code block started occurring. To test the behavior of them I created a new project which ends up getting the same errors.
I am using following code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using Microsoft.Office.Interop.Excel;
using Excel = Microsoft.Office.Interop.Excel;
namespace EA_Excel_ReadRange
{
class Program
{
static void Main(string[] args)
{
Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(@"PathToXslx");
Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1];
Excel.Range xlRange = xlWorksheet.UsedRange;
int rowCount = xlRange.Rows.Count;
int colCount = xlRange.Columns.Count;
for (int i = 1; i <= rowCount; i++)
{
for (int j = 1; j <= colCount; j++)
{
if (j == 1)
Console.Write("\r\n");
if (xlRange.Cells[i, j] != null && xlRange.Cells[i, j].Value2 != null)
Console.Write(xlRange.Cells[i, j].Value2.ToString() + "\t");
}
}
GC.Collect();
GC.WaitForPendingFinalizers();
Marshal.ReleaseComObject(xlRange);
Marshal.ReleaseComObject(xlWorksheet);
xlWorkbook.Close();
Marshal.ReleaseComObject(xlWorkbook);
xlApp.Quit();
Marshal.ReleaseComObject(xlApp);
}
}
}
I can run the code one time, where I get warned if that has not been found, that I should check if it is there, etc. After that one time I get following errors in VS 2019 Community. I checked the taskmanager as well, but there is no such process as it is described in the error messages.
Could not copy "obj\Debug\EA_Excel_ReadRange.exe" to "bin\Debug\EA_Excel_ReadRange.exe". Exceeded retry count of 10. Failed. The file is locked by: "EA_Excel_ReadRange.exe (21944)" EA_Excel_ReadRange
&
Unable to copy file "obj\Debug\EA_Excel_ReadRange.exe" to "bin\Debug\EA_Excel_ReadRange.exe". The process cannot access the file 'bin\Debug\EA_Excel_ReadRange.exe' because it is being used by another process. EA_Excel_ReadRange
Please explain why these errors are occuring and how I can fix them so the code will run. I just recently started programming in C# so I might have missed something in my code that is causing those errors.
Let me know if I need to clarify something.
EDIT The file I am using was downloaded from a Excel online company sheet on Sharepoint on Premises