1

我已经构建了一个小型 WPF 应用程序,它允许用户上传文档,然后选择一个来显示。

以下是文件复制的代码。

    
public static void MoveFile( string directory, string subdirectory)
{
    var open = new OpenFileDialog {Multiselect = false, Filter = "AllFiles|*.*"};
    var newLocation = CreateNewDirectory( directory, subdirectory, open.FileName);

    if ((bool) open.ShowDialog())
        CopyFile(open.FileName, newLocation);
    else
        "You must select a file to upload".Show();
}

private static void CopyFile( string oldPath, string newPath)
{
 if(!File.Exists(newPath))
  File.Copy(oldPath, newPath);
 else
  string.Format("The file {0} already exists in the current directory.", Path.GetFileName(newPath)).Show();
}
    

该文件被顺利复制。但是,当用户尝试选择他们刚刚复制的文件以显示时,找不到文件异常。调试后,我发现动态图像的 UriSource 正在将相对路径“Files{selected file}”解析为上面代码中的文件选择刚刚浏览的目录,而不是看起来像的应用程序目录它应该。

This problem only occurs when a newly copied file is selected. 如果您重新启动应用程序并选择新文件,它工作正常。

这是动态设置图像源的代码:

    
//Cover = XAML Image
Cover.Source(string.Format(@"Files\{0}\{1}", item.ItemID, item.CoverImage), "carton.ico");

...

public static void Source( this Image image, string filePath, string alternateFilePath)
{
    try
 {image.Source = GetSource(filePath);}
    catch(Exception)
 {image.Source = GetSource(alternateFilePath);}
}

private static BitmapImage GetSource(string filePath)
{
    var source = new BitmapImage();
    source.BeginInit();
    source.UriSource  = new Uri( filePath, UriKind.Relative);
    //Without this option, the image never finishes loading if you change the source dynamically.
    source.CacheOption = BitmapCacheOption.OnLoad;
    source.EndInit();
    return source;
}
    

我难住了。任何想法将不胜感激。

4

2 回答 2

1

尽管我没有直接的答案,但您应该谨慎对待允许人们上传文件的情况。我在一个研讨会上,他们有好与坏的黑客来模拟现实生活中的漏洞。一种是允许上传文件。他们上传了恶意的 asp.net 文件,并在图像最终呈现给用户的地方直接调用这些文件,并最终接管了系统。您可能想以某种方式验证允许哪些类型的文件,并且可能已存储在 Web 服务器的非执行目录中。

于 2010-01-07T14:44:20.963 回答
1

事实证明,我的 openfiledialogue 的构造函数中缺少一个选项。对话正在更改当前目录,这导致相对路径解析不正确。

如果将打开的文件替换为以下内容:


var open = new OpenFileDialog{ Multiselect = true, Filter = "AllFiles|*.*", RestoreDirectory = true};

问题已解决。

于 2010-01-08T14:19:04.523 回答