我已经构建了一个小型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}'解析为上述代码中文件选择的目录,而不是Application目录,因为它看起来像这应该。
仅当选择新复制的文件时才会出现此问题。如果您重新启动应用程序并选择新文件,它工作正常。
这里是一个动态设置图像源代码:
//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;
}
我难倒。任何想法将不胜感激。
你说得对,那可能是一个安全异常,但是这个应用程序正在本地运行,所以安全性不是问题。谢谢你的提醒。 – Jeremy 2010-01-07 14:53:05