0

I have an really annoying propblem. I am displaying a PDF File from my local Computer memory with an C#/WPF - WebBrowser. Later in my Code I want to change this PDF file, but when I try this, there comes an error message, which says the file is accessed by another process but I don't have another process that accesses the file.

Code to display PDF C#:

var documentpath = new Uri(@"C:\Users\frzrj\Desktop\test.pdf" + "#toolbar=0&navpanes=0&zoom=50");
documentView.Source = documentpath;

Code where I try to change the file (C#):

File.WriteAllBytes(@"C:\Users\frzrj\Desktop\test.pdf", bytes);

Error when I trie to change the file:

System.IO.IOException: 'The process cannot access the file 'C:\Users\frzrj\Desktop\test.pdf' because it is being used by another process.'

What I tried so far: I tried several things but they didn't work. I tried to use documentView.Source = null before editing the file, but this didn't work. And I tried to Dispose the WebBrowser with documentView.Dispose. This works, but after editing the file I can't display it anymore because I get the error that I can't use disposed elements.

Error after I used the Dispose-Methode:

System.ObjectDisposedException: 'Cannot access a disposed object.'

Has anybody an idea or a solution regardning this problem?

thanks in advance

  • if you dispose the documentView object, the system is expecting that you won't use it again, ever. If you need to display it again, you must create a new documentView. – Martin Verjans Aug 14 '20 at 13:06
  • @Martin Verjans do I have to create a new one or just initialize the documentView new – Jakob Rindberger Aug 14 '20 at 13:08
  • No you must create a new one. You don't know what happens when calling Dispose so basically the object becomes garbage and should not be used anymore. It is better to create a new instance. – Martin Verjans Aug 14 '20 at 13:40
  • How about unlock the pdf file before update it? like [How can I unlock a file that is locked by a process in .NET](https://stackoverflow.com/questions/242882/how-can-i-unlock-a-file-that-is-locked-by-a-process-in-net) – DasiyTian_1203 Aug 18 '20 at 08:39

0 Answers0