C# 设置图像源时出现相对路径分辨率问题
我已经构建了一个小的WPF应用程序,允许用户上传文档,然后选择一个进行显示 以下是文件副本的代码C# 设置图像源时出现相对路径分辨率问题,c#,wpf,relative-path,imagesource,C#,Wpf,Relative Path,Imagesource,我已经构建了一个小的WPF应用程序,允许用户上传文档,然后选择一个进行显示 以下是文件副本的代码 public static void MoveFile( string directory, string subdirectory) { var open = new OpenFileDialog {Multiselect = false, Filter = "AllFiles|*.*"}; var newLocation = CreateNewDirectory( direct
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}”解析为上面代码中的file select刚刚浏览的目录,而不是应用程序目录
此问题仅在选择新复制的文件时发生。如果重新启动应用程序并选择新文件,它将正常工作
以下是动态设置图像源的代码:
//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;
}
我被难住了。如果您有任何想法,我们将不胜感激。虽然我没有直接的答案,但您应该谨慎,这样才能允许人们上传文件。我参加了一个研讨会,他们让好黑客和坏黑客模拟现实生活中的漏洞攻击。一种是允许上传文件。他们上传了恶意的asp.net文件,并在文件更新时直接调用这些文件,最终将图像呈现给用户,并最终接管了一个系统。您可能希望以某种方式验证允许哪些类型的文件,以及哪些类型的文件存储在web服务器的非执行目录中。事实证明,我在openfiledialogue的构造函数中缺少一个选项。对话正在更改当前目录,导致相对路径解析不正确 如果将打开的文件替换为以下内容:
var open = new OpenFileDialog{ Multiselect = true, Filter = "AllFiles|*.*", RestoreDirectory = true};
问题已解决。您说得对,这可能是一个安全异常,但此应用程序正在本地运行,因此安全性不是问题。谢谢你的提醒。