사용자가 문서를 업로드 한 다음 표시하도록 선택할 수있는 작은 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}'을 응용 프로그램 디렉토리 대신 위의 코드에서 파일 선택에서 찾은 디렉토리로 확인하는 것으로 나타났습니다. 그것은해야한다.
이 문제는 새로 복사 한 파일을 선택한 경우에만 발생합니다. 응용 프로그램을 다시 시작하고 새 파일을 선택하면 제대로 작동합니다.
//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