Reputation: 331
I have a process that takes some varying time to execute. The proceeding part of the code depends on its results. The process creates a printable file (PRN) file. The proceeding section then reads that file and returns its bytes contents.
When i put a breakpoint at the using statement, i get to read the bytes of the created file and return them to where they are being requested. But when i execute as usual, i get the error.
_ The process cannot access the file 'linkToFile' because it is being used by another process _
lbl.PrintSettings.PrinterName = printerName;
byte[] fileBytes = null;
Task.Run(() => { lbl.Print(int.Parse(qty)); }).Wait(2000);
using (var strm = File.Open(outPutPrintFile,
FileMode.Open, FileAccess.Read, FileShare.Read))
{
using (var ms = new MemoryStream())
{
strm.CopyTo(ms);
fileBytes = ms.ToArray();
}
}
return Ok(fileBytes);
I tried to put the part that executes longer in a Task-Wait part but still getting the same error.
Upvotes: 0
Views: 84
Reputation: 77866
Try using Fileshare.ReadWrite
instead of FileShare.Read
. It's not for some unknown reason as you commented but ReadWrite
make sure that further Read/Write operations can be done on opening the file. From your posted code it looks to be the option to choose.
Upvotes: 2