2016-11-16 5 views
0

을 잠급니다.BitmapImage.UriSource 내 UWP 응용 프로그램에서 로컬 파일

보기

var bitmap = new BitmapImage(); 
bitmap.UriSource = new Uri("ms-appdata:///local/image.jpg"); 

모델

private async UpdateImage() 
{ 
    // this line throws! 
    var file = await ApplicationData.Current.LocalFolder.CreateFileAsync("image.jpg", CreationCollisionOption.ReplaceExisting); 
    ... 
} 

어떻게 그 UriSource와로 사용되는 로컬 파일 잠금에서 BitmapImage을 중지 할 수 있습니다?

답변

0

이 파일은보기의 BitmapImage에 의해 잠겨 있기 때문에 UnauthorizedAccessException 예외 '액세스가 거부되었습니다'가 발생합니다.

BitmapImage.UriSource 소스를 BitmapImage에 설정하는 속성을 사용하는 경우 파일의 파일 스트림이 사용 중이어야합니다. 이를 해결하기 위해 우리는 파일 스트림을 IRandomAccessStream으로 읽을 수 있습니다.이 경우 파일 스트림을 처리하여 파일 잠금을 해제 할시기를 제어 할 수 있습니다. 갱신 코드는 다음과 같습니다

private async void btncreate_Click(object sender, RoutedEventArgs e) 
{ 
    var file = await ApplicationData.Current.LocalFolder.CreateFileAsync("image.jpg", CreationCollisionOption.ReplaceExisting); 
} 

private async void Page_Loaded(object sender, RoutedEventArgs e) 
{ 
    var bitmap = new BitmapImage(); 
    //bitmap.UriSource = new Uri("ms-appdata:///local/image.jpg"); 
    //imgshow.Source = bitmap; 
    StorageFile imagefile = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appdata:///local/image.jpg")); 
    using (IRandomAccessStream stream = await imagefile.OpenAsync(FileAccessMode.Read)) 
    { 
     bitmap.SetSource(stream); 
     imgshow.Source = bitmap; 
    } 
} 
0

이 시도 :

var bitmap = new BitmapImage(); 
bitmap.BeginInit(); 
bitmap.CacheOption = BitmapCacheOption.OnLoad; 
bitmap.CreateOption = BitmapCreateOptions.IgnoreImageCache; 
bitmap.UriSource = new Uri("ms-appdata:///local/image.jpg");  
bitmap.EndInit(); 
+0

'bitmap.CacheOption'은 그렇게 할 것이지만, 내가 아는 한 UWP에서는 지원하지 않습니다. – Vitaly

+0

감사합니다.하지만 불행히도 UWP에는 'CacheOption' 속성이 없습니다. – Vitaly

+1

죄송합니다, 내가 UWP인지 알지 못했습니다. Model UpdateImage를 호출하기 전에 View의 BitMapImage 객체를 "재설정"한 다음 업데이트 된 이미지보기에서 다시로드해야합니다. –

0

의 주변 작업 - bitmap.SetSource 암시 비동기이기 때문에 "Sunteen 우 MSFT는"거의 정확, SetSource이 완료되기 전에 스트림이 배치받을 수 있습니다. 명시 적 함수 SetSourceAsync를 사용하고 기다려야합니다.

어쨌든이 솔루션은 많은 메모리를 사용합니다. URI 솔루션은 어떻게 든 친숙합니다 (이유를 알고 싶어합니다).

URI 솔루션은 결정할 수없는 오랜 시간 동안 파일을 잠급니다. 다른 솔루션은 파일을 잠그지 않지만 많은 메모리를 불합리한 시간 동안 할당합니다.

내 솔루션을 공유 할 수 있습니다 : 원래 파일을 임시 폴더에 복사 한 다음 해당하는 Uri로 엽니 다. 그러나 그때 파일은 저에게 지워지지 않을 것이고, 이것은 많은 디스크 공간을 줄여 줄 것입니다.

비슷한 문제가있는 사람이 있습니까? 다른 솔루션?

관련 문제