文件重命名不起作用

时间:2013-07-09 05:26:18

标签: c# string file-io

FileInfo _fileinfo = new FileInfo(@"D:\Projects\LSImage\" + dt.Rows[0]["ApplicationImage"].ToString());         
File.Move(_fileinfo.FullName, _fileinfo.FullName.ToString().Replace(_fileinfo.FullName, dt.Rows[0]["ApplicationID"].ToString() + dt.Rows[0]["ApplicationImage"].ToString()));

它正在抛出错误

  

当该文件已存在时无法创建文件。

我必须使用来自数据库的applicationId重命名LsImages中的图像,所以我在前面添加应用程序,然后从数据库中添加applicationimage名称

5 个答案:

答案 0 :(得分:1)

您正在替换完整的字符串:

File.Move(_fileinfo.FullName, _fileinfo.FullName .ToString()。替换( _fileinfo.FullName ,dt.Rows [0] [“ApplicationID”] .ToString()+ dt.Rows [0] [“ApplicationImage”]。ToString()));

你确定你不想要这个吗?:

File.Move(_fileinfo.FullName, _fileinfo.FullName.ToString().Replace(dt.Rows[0]["ApplicationImage"], dt.Rows[0]["ApplicationID"].ToString() + dt.Rows[0]["ApplicationImage"].ToString()));

或者:

File.Move(_fileinfo.FullName, _fileinfo.FullName.Replace(_fileinfo.Name, dt.Rows[0]["ApplicationID"].ToString() + dt.Rows[0]["ApplicationImage"].ToString()));

答案 1 :(得分:1)

var defaultPath=@"D:\Projects\LSImage";
var appImage=dt.Rows[0]["ApplicationImage"].ToString();
var appId=dt.Rows[0]["ApplicationID"].ToString();
var srcFile=Path.Combine(defaultPath,appImage);
var dstFile=Path.Combine(defaultPath,appId + appImage);
FileInfo _fileinfo = new FileInfo(srcFile);  // This isn't needed to rename
File.Move(srcFile,dstFile);

答案 2 :(得分:0)

FileInfo _fileinfo = new FileInfo(@"D:\Projects\LSImage\" + dt.Rows[0]["ApplicationImage"].ToString());
try
{
    File.Move(_fileinfo.FullName, _fileinfo.FullName.ToString().Replace(_fileinfo.FullName, dt.Rows[0]["ApplicationID"].ToString() + dt.Rows[0]["ApplicationImage"].ToString()));
}
catch(Exception ex)
{
    throw new Exception(String.Format("Trying to rename {0} to {1} failed!",_fileinfo.Fullname,dt.Rows[0]["ApplicationID"].ToString() + dt.Rows[0]["ApplicationImage"].ToString()));
}

然后告诉我们它的报道。

答案 3 :(得分:0)

看起来您正在尝试将ApplicationID添加到文件的前面。如果是这样,试试这个:

FileInfo _fileinfo = new FileInfo(@"D:\Projects\LSImage\" + dt.Rows[0]["ApplicationImage"].ToString());         

string appID = dt.Rows[0]["ApplicationID"].ToString();
string appImage = dt.Rows[0]["ApplicationImage"].ToString();
string newFullPath = @"D:\Projects\LSImage\" + appImage + appID;

File.Move(_fileinfo.FullName, newFullPath); 

答案 4 :(得分:0)

File.Move(_fileinfo.FullNmae,_fileinfo.FullName.Replace(_FileInfo.Name,dt.rows[0]["apid"].tostring() + dr.rows[0]["apname"].tosring()))