【发布时间】:2016-07-26 16:06:00
【问题描述】:
我正在处理的 ASP.NET MVC 程序的文件更新部分出现问题。基本前提是程序会从用户那里获取一个编辑过的图像,然后用新数据更新旧文件,保留旧名称。但是由于某种原因,当文件从临时文件夹移动到它应该去的文件夹时,它被保存为一个新文件,同时保留旧文件。 (例如,“foo 1-1.jpg”和“foo 1-1.jpg”存在于同一个文件夹中)。据我所知,这两个文件名是相同的。为什么会发生这种情况,我该如何做才能按预期首先删除旧文件?
我在移动之前获取了旧文件名,所以那里应该没有问题。也没有路径问题。
我不确定我传入的路径是否有问题,但我使用相同的方法来获取要移动到的文件路径,所以我不知道为什么 File.Delete( ) 而不是 File.Move()。
这里是有问题的代码:
/// <summary>
/// Move a number of files to a single directory, keeping their names
/// and overwriting if the switch is toggled.
/// Will ignore nonexistent files, and return false if the specified directory does not exist.
/// Returns true if it succeeded, false if it did not.
/// </summary>
/// <param name="filePaths">An array of filepath strings, </param>
/// <param name="saveDirectory">The path to the directory to use</param>
/// <param name="overWrite">Optional, defaults to false. Whether or not
/// to overwrite any existing files with the same name in the new directory.
/// If false, skips files that already exist in destination.</param>
/// <returns>bool</returns>
public static bool MoveSpecificFiles(string[] filePaths, string saveDirectory, bool overWrite = false)
{
//If the directory doesn't exist, error out.
if (!Directory.Exists(saveDirectory))
{
return false;
}
string fileName;
try
{
foreach (string filePath in filePaths)
{
//Check if the file to be moved exists. If it doesn't, skip it and go to the next one.
if (File.Exists(filePath))
{
fileName = Path.GetFileName(filePath);
//if the overwrite flag is set to true and the file exists in the new directory, delete it.
if (overWrite && File.Exists(saveDirectory + fileName))
{
//WHERE THE ERROR IS OCCURING
File.Delete(saveDirectory + fileName);
}
//If the file to be moved does not exist in the new location, move it there.
//This means that duplicate files will not be moved.
if (!File.Exists(saveDirectory + fileName))
{
File.Move(filePath, saveDirectory + fileName);
}
}
//throw new ArgumentException();
}
}
catch (Exception)
{
//check = saveDirectory + " " + Path.GetFileName(filePaths[0]);
return false;
}
return true;
}
任何帮助将不胜感激。
【问题讨论】:
-
您收到的错误信息是什么?
-
没有具体的错误信息,只是意外行为。 File.Delete 没有找到指定的文件,可以推断它没有产生任何异常,因为图像正在被移动。问题是它应该找到旧文件,因为在以前的方法中,我正在获取旧文件的名称以传递给该文件。
-
你确定
overWrite变量值是真的吗? -
是的,因为我在调用方法时这样声明:if (FileManipExtensions.MoveSpecificFiles(filesMove, newDirPath, true)) 编辑:方法错误!
标签: c# asp.net-mvc file-io