Surya sasidhar
Surya sasidhar

Reputation: 30293

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 the renamed file in a folder which is in Solution Explorer.

Upvotes: 9

Views: 29975

Answers (3)

Bhaskar
Bhaskar

Reputation: 10681

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.

Upvotes: 9

Marvin Smit
Marvin Smit

Reputation: 1

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.

Upvotes: 0

Winston Smith
Winston Smith

Reputation: 21884

You can do it with the File.Move method eg:

string oldFileName = "MyOldFile.txt";
string newFileName = "MyNewFile.txt";
File.Move(oldFileName, newFileName);

Upvotes: 10

Related Questions