2012-07-16 40 views
2

在我的Windows Phone應用程序中,我有.mp4文件作爲內容。我如何檢查我是否真的在我的應用程序中擁有它?如何檢查存在的內容文件?

更新 例如,在我來說,我有來源:/res/9a8be1550f818223edcfc5ab6d765cec.mp4

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

如果我檢查這種方式有一個例外:

+0

你 「擁有它」?目前尚不清楚您是在隔離存儲中還是隻在您的項目中嵌入。 – 2012-07-16 11:31:42

+0

如果它作爲內容附加,它就在那裏,或者你做得不對。不應該檢查它。 – 2012-07-16 12:01:28

回答

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 
} 
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 
} 
+0

你見過他的評論嗎?//路徑不應該以斜槓開頭? – hofmeister 2016-11-04 09:14:11

+0

我試過路徑'「/images/MenuIcon.png」'和'「images/MenuIcon.png」'並且都導致* System.IO.IOException * – 2016-11-04 11:21:23