我已经构建了一个小型 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;
}
我难住了。任何想法将不胜感激。