设置图像源时相对路径分辨率的问题
-
19-09-2019 - |
题
我已经构建了一个小型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;
}
我很难过。任何想法都将不胜感激。
解决方案 2
事实证明,我缺少OpenFileDialogue的构造函数中的选项。对话正在改变当前目录,该目录导致相对路径错误地解决。
如果您用以下内容替换打开文件:
var open = new OpenFileDialog{ Multiselect = true, Filter = "AllFiles|*.*", RestoreDirectory = true};
问题已经解决。
其他提示
尽管我没有直接的答案,但您应该谨慎行事,以允许人们上传文件。我当时在一个研讨会上,他们有好与坏黑客来模拟现实生活中的漏洞。一个人因此可以上传文件。他们上传了恶意ASP.NET文件,并在最终向用户呈现图像的新文件时直接调用文件,并最终能够接管系统。您可能需要以某种方式验证允许哪些类型的文件,并且可能已存储在Web服务器的非外观目录中。
不隶属于 StackOverflow