2010-01-07 69 views
1

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

我難倒。任何想法將不勝感激。

回答

1

原來我在我的openfiledialogue的構造函數中丟失了一個選項。該對話正在改變導致相對路徑不正確解析的當前目錄。

如果替換爲下面打開的文件:


var open = new OpenFileDialog{ Multiselect = true, Filter = "AllFiles|*.*", RestoreDirectory = true}; 

問題已解決。

1

儘管我沒有直接的答案,但您應該謹慎,以便允許用戶上傳文件。我在一個研討會上,他們有很好的vs不好的黑客來模擬現實生活中的漏洞。一個是允許文件被上傳。他們上傳了惡意的asp.net文件,並直接調用這些文件,因爲他們最終將圖像最終呈現給用戶,並最終能夠接管系統。你可能想驗證什麼類型的文件被允許,可能已經存儲在你的Web服務器的非執行目錄中。

+0

你說得對,那可能是一個安全異常,但是這個應用程序正在本地運行,所以安全性不是問題。謝謝你的提醒。 – Jeremy 2010-01-07 14:53:05