I’m trying to create a csv file from an excel file using MS Excel Interop in my C#/Winforms app.
Am getting this error on SaveAs method in the code below.
‘The file could not be accessed. Try one of the following:
• Make sure the specified folder exists. • Make sure the folder that
contains the file is not read-only. • Make sure the file name does
not contain any of the following characters: < > ? [ ] : | or
* • Make sure the file/path name doesn’t contain more than 218
characters.’z
I tried setting readonly to false in Workbook’s Open(…) method as per:
Problem saving excel file after inserting data , but still getting the same error.
In my code, the csv file path was:C:\
If I change the csv file path to C:\SomeFolder or some shared UNC path, then I dont get this error.
Please advise.COuld there be some permissions issues with C drive?
Heres the code:
xlApp = new Microsoft.Office.Interop.Excel.Application();
xlApp.DisplayAlerts = false;
xlApp.Visible = false;
wbkSrc = xlApp.Workbooks.Open(m_sSrcFil,
Type.Missing, false, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing);
wstSrc = (Worksheet)wbkSrc.Worksheets[sSrcSht];
//wstSrc.Activate();
rngWork = wstSrc.Cells.get_Range("H:H", System.Reflection.Missing.Value);
rngWork.NumberFormat = "General";
dteTmpDate = Convert.ToDateTime(m_sBusDate);
sTmpFileName = m_sSrcFil.Substring(0, m_sSrcFil.IndexOf(".")) + "_" +
m_sUserName + "_" + dteTmpDate.ToString("yyyy_MM_dd") + ".Csv";
wstSrc.SaveAs(sTmpFileName, XlFileFormat.xlCSV, Type.Missing,
Type.Missing, true, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing);
Clearly
sTmpFileNameis an invalid path. The error message tells you that. Perhapsm_sUserNamecontains characters that are not allowed. Perhaps it is aDOMAIN\USERformat user name. Perhaps the file name really is too long. Or perhaps something else is up. Take a look at the actual value ofsTmpFileNameand you will have your explanation.As an aside, your code is mistaken in using
SubStringandIndexOf(".")to get the filename without the extension. Filenames can have multiple periods in them. The extension is simply that text after the final period. Consider these file names and how your code will deal with them:Instead you should use
Path.GetFileNameWithoutExtension.