如何检查内容文件是否存在?

时间:2012-07-16 11:24:40

标签: c# silverlight windows-phone-7

在我的Windows Phone应用程序中,我将.mp4文件作为内容。如何检查我的应用程序中是否真的有它?

更新 例如在我的情况下,我有来源:/res/9a8be1550f818223edcfc5ab6d765cec.mp4

if (File.Exists(localPath))
{
    myMediaElement.Source = new Uri(localPath, UriKind.Relative);
}

如果我这样检查有一个例外:

2 个答案:

答案 0 :(得分:3)

System.Windows.Resources.StreamResourceInfo sr;  
sr = Application.GetResourceStream(new Uri("images/MenuIcon.png", UriKind.Relative)); // path should NOT begin with a slash  
if (sr == null)  
{  
    // doesn't exist  
}  
else  
{  
    // exists  
} 

答案 1 :(得分:0)

来自用户“revolutionkpi”的回答可能导致System.IO.IOException,更好的是添加try-catch块:

System.Windows.Resources.StreamResourceInfo sr; 
try {
    sr = Application.GetResourceStream(new Uri("/images/MenuIcon.png",UriKind.Relative));
    if (sr == null)  {  
        // doesn't exist  
    }
    else{  
        // exists  
    } 
}
catch (Exception e) {
    // doesn't exist
}

Edit1:更漂亮的解决方案

var uri = new Uri("/images/MenuIcon.png", UriKind.Relative);
ImageSource image = null;

try
{
    if (Application.GetResourceStream(uri) != null)
    {
        image = new BitmapImage(uri); 
    } 
}
catch { }

if (image == null) {
    // doesn't exist  
}