Monday, October 29, 2012

How to detect file is open with silverlight saveDialog for C#?

How to detect file is open with silverlight saveDialog for C#?

If a file is open by another application, and then I try to save it through the Silverlight SaveDialog, I can catch the error with an exception but after that I get this error.

Line: 57 Error: Unhandled Error in Silverlight Application Code: 4004
Category: ManagedRuntimeError
Message: System.InvalidOperationException: This operation can only occur on the UI Thread. at System.Windows.Hosting.NativeHost.VerifyThread() at System.Windows.SaveFileStream.Dispose(Boolean disposing) at System.IO.FileStream.Finalize()

I would prefer to detect that the file is open, but can't seem to do that. I tried fs.CanWrite, but it returns true, even when the file is open by another application.

EDIT: Here is a post on the silverlight forum that seems to explain what is happening, although they think it's just Office files. I'm having the problem with a PDF file.

Here is my code:

    public void PDFSaveFile(bool success)     {         // silverlight requires saveFileDialog to be user-initiated,          // so this is called from the OK button of a pop-up window         // ignore success, we only gave an OK option         byte[] fileBytes = doc.ToPDF().ToArray();         PDFClose();          try         {             SaveFileDialog saveFileDlg = new SaveFileDialog();             saveFileDlg.Filter = "PDF files (*.pdf)|*.pdf";             bool? dialogResult = saveFileDlg.ShowDialog();             if (dialogResult == true)             {                 using (var fs = saveFileDlg.OpenFile())                 {                     fs.Write(fileBytes, 0, fileBytes.Length);                     fs.Close();                 }             }         }         catch (Exception ex)         {             Log.HandleInternalError(string.Format("Unable to save file: {0}",ex.Message));         }     } 

Answers & Comments...

Answer: 1

You can use FileInfo.Open if return a IOException = File already opened

FileInfo.Open

by : Ozan Cakırhttp://stackoverflow.com/users/1763013




No comments:

Post a Comment

Send us your comment related to the topic mentioned on the blog