Writing in files ASP.NET C# and NOT locking them afterwards
<p>I am getting this error: The process cannot access the file (...) because it is being used by another process.
I have tried to use 
<code>File.WriteAllText</code>; </p>

<pre><code>StreamWriter sw = new StreamWriter(myfilepath);
                sw.Write(mystring);
                sw.Close();
                sw.Dispose();
</code></pre>

<p>;</p>

<pre><code>using (FileStream fstr = File.Create(myfilepath))
                {
                StreamWriter sw = new StreamWriter(myfilepath);
                sw.Write(mystring);
                sw.Close();
                sw.Dispose();
                fstr.Close();
                }
</code></pre>

<p>All I am trying to do is to access a file, write on it, then close it. I might be making a silly mistake but I would like to understand what I am doing wrong and why. How to make sure that the file is closed and not to cause this error again.</p>

<p>Helped by the answers so far I did this:</p>

<pre><code>using (FileStream fstr = File.Open(myfilepath,FileMode.OpenOrCreate,FileAccess.ReadWrite))
                {
                    StreamWriter sw = new StreamWriter(fstr);
                    sw.Write(mystring);
                    sw.Close();


                }
</code></pre>

<p>It seems to be better because it seems to close/stop the process of my file if I try to access another file on the second time I access the page. But if I try to access the same file on a second time, it gives me the error again.</p>
