我已經構建了一個小型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