Asp.net 通过在以前的名称中添加当前日期和时间来重命名文件
如果文件夹中已经存在文件名,我想重命名用户上载的文件名Asp.net 通过在以前的名称中添加当前日期和时间来重命名文件,asp.net,file,file-upload,save,file-rename,Asp.net,File,File Upload,Save,File Rename,如果文件夹中已经存在文件名,我想重命名用户上载的文件名 string existpath = Server.MapPath("~\\JD\\"); DirectoryInfo ObjSearchDir = new DirectoryInfo(existpath); if (ObjSearchFile.Exists) { foreach (FileInfo fi in ObjSearchFile.GetFiles()) { fi.CopyTo(existfile,
string existpath = Server.MapPath("~\\JD\\");
DirectoryInfo ObjSearchDir = new DirectoryInfo(existpath);
if (ObjSearchFile.Exists)
{
foreach (FileInfo fi in ObjSearchFile.GetFiles())
{
fi.CopyTo(existfile, false);
}
}
此代码无效,无法找到现有文件。从文章中,CopyTo方法将仅设置是否覆盖现有文件。您应该使用以下命令检查文件是否存在于目标目录中:
File.Exists(path)
如果是,您需要重命名正在使用的文件(我不确定您得到的ObjSeachFile对象是什么),然后尝试重新保存它。还要记住,如果您有另一个同名文件,您应该重新检查该文件是否存在。这里肯定
CopyTo()
不起作用,因为您已将覆盖选项设置为false
(CopyTo()的第二个参数)
。如果文件存在且覆盖为false,则会通过以下行引发IOException
:fi.CopyTo(existfile,false);
。检查
你可以参考下面两个代码来完成同样的任务。你喜欢哪一个取决于你。你认为哪一个更好
方法1:使用File.Copy()、File.Delete()
。请参阅&
在这种情况下,您可以指定相对路径和绝对路径。相对路径将作为相对于当前工作目录的路径
方法2:使用FileInfo.MoveTo
。请参阅
DirectoryInfo ObjSearchFile=new DirectoryInfo(existpath);FileInfo[]infos=ObjSearchFile.GetFiles();foreach(FileInfo f in infos){//File.Move(f.FullName,f.FullName.ToString().Replace(“abc_”),System.IO.File.Move(existfile,savefile);if(f.Name.Equals(chkfile)){System.IO.File.Copy(savefile,existfile,false);}
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);
}
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());
}
}