【问题标题】:A problem with Relative Path Resolution when setting an Image Source设置图像源时的相对路径分辨率问题
【发布时间】:2010-01-07 14:35:51
【问题描述】:

我已经构建了一个小型 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}”解析为上面代码中的文件选择刚刚浏览的目录,而不是看起来像的应用程序目录它应该。

此问题仅在选择新复制的文件时发生。如果您重新启动应用程序并选择新文件,它就可以正常工作。

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

//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; }

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

【问题讨论】:

    标签: c# wpf relative-path imagesource


    【解决方案1】:

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

    【讨论】:

    • 你是对的,这可能是一个安全异常,但是这个应用程序是在本地运行的,所以安全不是问题。不过还是谢谢你的提醒。
    【解决方案2】:

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

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

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

    问题已解决。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-02-20
      • 1970-01-01
      • 1970-01-01
      • 2013-05-08
      • 2023-04-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多