Reputation: 319
I would like to rename the filename that has been uploaded by a user if the file name already exists in a folder.
string existpath = Server.MapPath("~\\JD\\");
DirectoryInfo ObjSearchDir = new DirectoryInfo(existpath);
if (ObjSearchFile.Exists)
{
foreach (FileInfo fi in ObjSearchFile.GetFiles())
{
fi.CopyTo(existfile, false);
}
}
this code is not working, it is not able to find existing file.
Upvotes: 2
Views: 2683
Reputation: 10565
Here definitely CopyTo()
is not working because you have set OverWrite option as false
( 2nd parameter of CopyTo()
. If the file exists and overwrite is false, an IOException
is thrown by line: fi.CopyTo(existfile, false);
. Check MSDN
You may refer below two codes for doing the same task. Which one you prefer its upto you. Any thoughts which one is better ?
Method 1: Using File.Copy(), File.Delete()
. Refer MSDN_1 & MSDN_2
string sourceDir = @"c:\myImages";
string[] OldFileList = Directory.GetFiles(sourceDir, "*.jpg");
foreach (string f in OldFileList)
{
// Remove path from the file name.
string oldFileName = f.Substring(sourceDir.Length + 1);
// Append Current DateTime
String NewFileName= oldFileName + DateTime.Now().ToString();
File.Copy(Path.Combine(sourceDir,oldFileName),
Path.Combine(sourceDir,NewFileName);
File.Delete(oldFileName);
}
You can specify relative as well as absolute paths in this case. Relative path will be taken as relative to your current working directory.
Method 2: Using FileInfo.MoveTo
. Refer MSDN
protected void btnRenameOldFiles_Click(object sender, System.EventArgs e)
{
string source = null;
//Folder to rename files
source = Server.MapPath("~/MyFolder/");
foreach (string fName in Directory.GetFiles(source)) {
string dFile = string.Empty;
dFile = Path.GetFileName(fName);
string dFilePath = string.Empty;
dFilePath = source + dFile;
FileInfo fi = new FileInfo(dFilePath);
//adding the currentDate
fi.MoveTo(source + dFile + DateTime.Now.ToString());
}
}
Upvotes: 1
Reputation: 3012
From this article, the CopyTo method will only set whether you want to overwrite an existing file. What you should be doing is checking if the file exists in the target directory by using:
File.Exists(path)
If is does, you're need to rename the file you're working with (I'm not sure what that ObjSeachFile object you've got is) and then try re-saving it. Also bear in mind you should re-check if the file exists in case you've got another existing file with the same name.
Upvotes: 0