-2

I have the following problem:

I use this code to open a file and write to it:

using (FileStream fileStream = new FileStream(saveDir + @"\" +   saveFile, FileMode.Open, FileAccess.ReadWrite,FileShare.ReadWrite))
{
    StreamWriter streamWriter = new StreamWriter(fileStream);
    streamWriter.Write("Test");
    streamWriter.Close();
}

but in the "using" line it tells me that it can not open the file because it is used by another process but the file is not open and isn't used. What's wrong? I searched around this forum and the internet but I can't find a solution.

Vignesh.N
  • 2,618
  • 2
  • 25
  • 33
HT085
  • 11
  • 4
  • 4
    `but the file is not open and isn't used` - are you sure? Such messages are very rarely lying... – Christoph Fink Jan 27 '15 at 13:15
  • 1
    Clearly Windows thinks the file is in use. – Lasse V. Karlsen Jan 27 '15 at 13:16
  • no it's not used at all. How to solve that? – HT085 Jan 27 '15 at 13:17
  • How have you checked, that its not in use? – Christoph Fink Jan 27 '15 at 13:18
  • You can solve using Handle which displays information about open handles for any process in the system. https://technet.microsoft.com/en-us/sysinternals/bb896655.aspx or the GUI-based ProcessExplorer https://technet.microsoft.com/en-us/sysinternals/bb896653 – Alberto Spelta Jan 27 '15 at 13:19
  • How to check that? I created it via the File.Create Command. It's an empty file. I even closed VisualStudio and reopened it. The file is closed and I don't know what process should use the file. – HT085 Jan 27 '15 at 13:20
  • Are you creating the file in the same code as when you are trying to open it? If so, post all the relevant code – Bernd Linde Jan 27 '15 at 13:21
  • i know this. you think it isn't used but windows thinks so... sometimes a reboot is helpful. Check also (maybe more interesting with StreamWriter) that the file isn't readonly. – Jens Jan 27 '15 at 13:21
  • modify the filename and try again... – DrKoch Jan 27 '15 at 13:25
  • Ok thanks! I deleted a if command where he checks if the file exists and creates it otherwise. I used the OpenOrCreate Command. Now it works fine! – HT085 Jan 27 '15 at 13:26
  • This might be hold by w3p process or asp.net local webserver if you are using asp.net application. Explorer can also hold if you are checking if file has been created. – Amit Jan 27 '15 at 13:27

1 Answers1

0

You could try using FileMode.OpenOrCreate instead of creating the file "manually":

using (FileStream fileStream = new FileStream(saveDir + @"\" + saveFile, 
    FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
{
    StreamWriter streamWriter = new StreamWriter(fileStream);
    streamWriter.Write("Test");
    streamWriter.Close();
}
Christoph Fink
  • 22,727
  • 9
  • 68
  • 113