Click here to Skip to main content
15,912,329 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I have made a windows service that exports the data from database into an excel and then send it as an attachment in a mail.

I have set the timer that windows service needs to send it on Mon and Thursday.

I am facing an issue in the filename now..as in the file gets saved as 'C://abc.xlsx' in first call but in second call it says that it cannot acess the file 'C://abc.xlsx'.
I want that in second run the excel should be saved with a different name say 'C://abc_date.xlsx' where date is the current date on which the fresh excel is generated.

Can some help pls.

Thanks
Posted

1 solution

Hi,

you could just rename the filename before saving with this code:
C#
string fileName = "C:\\abc.xlsx";
string renamedFile = Path.GetFileNameWithoutExtension(fileName);
renamedFile = renamedFile += "_" + DateTime.Now.ToShortDateString() + Path.GetExtension(fileName);
MessageBox.Show(renamedFile);
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 16-Feb-11 0:54am    
Simple as that, 5,
--SA
Aksh@169 16-Feb-11 1:21am    
Thanks for your help but I am getting an error which is as below:- Microsoft Office Excel cannot access the file 'test_2/16/2011.xlsx'. There are several possible reasons: • The file name or path does not exist. • The file is being used by another program. • The workbook you are trying to save has the same name as a currently open workbook. Could not find a part of the path 'C:\Windows\system32\test_2\16\2011.xlsx'. The code i have written is as below:
string filepath, filename, fileExcel, renamedfile;
filepath = "C:\\test";
filename = filepath + @"\test.xlsx";
renamedfile = Path.GetFileNameWithoutExtension(filename);
renamedfile = renamedfile += "_" + DateTime.Now.ToShortDateString() + Path.GetExtension(filename);

----logic for generating excel
excelWorkbook.SaveCopyAs(renamedfile);


Any suggestions for this?
JF2015 16-Feb-11 1:38am    
Hi,

for this issue, you can try this modified solution:
string fileName = "C:\\abc.xlsx";
string renamedFile = Path.GetFileNameWithoutExtension(fileName);
renamedFile = Path.GetPathRoot(fileName) + renamedFile + "_" + DateTime.Now.ToString("dd.MM.yyyy") + Path.GetExtension(fileName);
MessageBox.Show(renamedFile);
This fixes your issue for me. I hope it helps.
Aksh@169 16-Feb-11 2:21am    
Thanks..it worked this way:)

I am also looking for one more thing if you could suggest something.

I intend to delete the obsolete excels(say last 10 excels) stored at the location specified due to size issue.
Can you please help in this?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900