Getting error on calling SaveAs method
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 sTmpFileName
is an invalid path. The error message tells you that. Perhaps m_sUserName
contains characters that are not allowed. Perhaps it is a DOMAIN\USER
format user name. Perhaps the file name really is too long. Or perhaps something else is up. Take a look at the actual value of sTmpFileName
and you will have your explanation.
As an aside, your code is mistaken in using SubString
and IndexOf(".")
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:
C:\My.Folder.Name\TheFile.xls
C:\MyFolder\TheFile.Name.xls
Instead you should use Path.GetFileNameWithoutExtension
.
Excel SaveAs is quite picky. Things like c:\folder\\file.csv
(note the double backslash) are accepted by File.Exists or when you open a workbook, but not when saving
Check your FilePath where you are saving if it is more than 218 characters then also you will get this error.
精彩评论