ユーザーがドキュメントをアップロードして、表示するドキュメントを選択できる小さな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{selectedfile}」を解決していることがわかりました。そうすべき。
この問題は、新しくコピーされたファイルが選択された場合にのみ発生します。アプリケーションを再起動して新しいファイルを選択すると、正常に機能します。
画像ソースを動的に設定するコードは次のとおりです。
//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;
}
私は困惑しています。どんな考えでもいただければ幸いです。