C# excel SaveAs file could not be accessed when sa

2019-08-15 19:15发布

Attempting to save an excel worksheet programmatically as a unique filename in a loop.

    private static DateTime csvtime = DateTime.Now;
    private static string time = csvtime.ToString("HH:mm:ss");
    private static string Path = @"C:\users\User\desktop\MonetaryEntry_"+time+".csv";
    mySheet = (Excel.Worksheet)myBook.Worksheets[1];


mySheet.SaveAs(Path, Microsoft.Office.Interop.Excel.XlFileFormat.xlCSV);

This fails with the following error

An unhandled exception of type 'System.Runtime.InteropServices.COMException' occurred in MonetaryEntryFormatting.exe

Additional information: 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.

however when I change the Path string to

private static string path = "@C:\users\user\desktop\MonetaryEntry_.csv";

it resolves.

The goal is to iterate through a loop saving each time as a unique *.csv file. Undetermined amount of .csv files will be generated each time.

a few notes;

writing to the desktop the user account I'm currently doing all the work in. If relevant, I copy a file on the desktop and paste as a different name and work from there.

I feel I might be missing something fairly simple as this kind of issue typically is..

1条回答
再贱就再见
2楼-- · 2019-08-15 19:37
private static DateTime csvtime = DateTime.Now;
private static string time = csvtime.ToString("HH_mm_ss");
private static string Path = @"C:\users\User\desktop\MonetaryEntry_"+time+".csv";
mySheet = (Excel.Worksheet)myBook.Worksheets[1];
mySheet.SaveAs(Path, Microsoft.Office.Interop.Excel.XlFileFormat.xlCSV);

this is going to work change the tostring. the : is not a character allowed in the path. (look at the 3rd suggestion of the error)

查看更多
登录 后发表回答