2010-01-07 70 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