How can I rename a file in ASP.NET?
In my project I want to rename the file before it is updating. For example a file in my system like Mycontact.xls
. I want to rename it as sasi.xls
(it is an excel file). How can I write the code in ASP.NET?
Actually I am using a fileupload control to get the file in and rename the file and upload t开发者_如何学编程he renamed file in a folder which is in Solution Explorer.
You can do it with the File.Move method eg:
string oldFileName = "MyOldFile.txt";
string newFileName = "MyNewFile.txt";
File.Move(oldFileName, newFileName);
C# does not provide a file rename function, unfortunately. Anyhow, the idea is to do this:
File.Copy(oldFileName, NewFileName);
File.Delete(oldFileName);
You can also use - File.Move
.
Be aware that when that code executes, the owner of the file will turn into the identity you have set on your Application Pool on which the website is running.
That account might not have enough permissions to 'create new' or 'delete' files.
I would advise you to place all read/writable files in a seperate location so you can control the security settings seperately on that part. This will also split off the 'only readable files/executables' (like the aspx and such) from the 'read/writable' files.
精彩评论