File being used by another process after using File.Create()












96















I'm trying to detect if a file exists at runtime, if not, create it. However I'm getting this error when I try to write to it:




The process cannot access the file 'myfile.ext' because it is being used by another process.




string filePath = string.Format(@"{0}M{1}.dat", ConfigurationManager.AppSettings["DirectoryPath"], costCentre); 
if (!File.Exists(filePath))
{
File.Create(filePath);
}

using (StreamWriter sw = File.AppendText(filePath))
{
//write my text
}


Any ideas on how to fix it?










share|improve this question





























    96















    I'm trying to detect if a file exists at runtime, if not, create it. However I'm getting this error when I try to write to it:




    The process cannot access the file 'myfile.ext' because it is being used by another process.




    string filePath = string.Format(@"{0}M{1}.dat", ConfigurationManager.AppSettings["DirectoryPath"], costCentre); 
    if (!File.Exists(filePath))
    {
    File.Create(filePath);
    }

    using (StreamWriter sw = File.AppendText(filePath))
    {
    //write my text
    }


    Any ideas on how to fix it?










    share|improve this question



























      96












      96








      96


      11






      I'm trying to detect if a file exists at runtime, if not, create it. However I'm getting this error when I try to write to it:




      The process cannot access the file 'myfile.ext' because it is being used by another process.




      string filePath = string.Format(@"{0}M{1}.dat", ConfigurationManager.AppSettings["DirectoryPath"], costCentre); 
      if (!File.Exists(filePath))
      {
      File.Create(filePath);
      }

      using (StreamWriter sw = File.AppendText(filePath))
      {
      //write my text
      }


      Any ideas on how to fix it?










      share|improve this question
















      I'm trying to detect if a file exists at runtime, if not, create it. However I'm getting this error when I try to write to it:




      The process cannot access the file 'myfile.ext' because it is being used by another process.




      string filePath = string.Format(@"{0}M{1}.dat", ConfigurationManager.AppSettings["DirectoryPath"], costCentre); 
      if (!File.Exists(filePath))
      {
      File.Create(filePath);
      }

      using (StreamWriter sw = File.AppendText(filePath))
      {
      //write my text
      }


      Any ideas on how to fix it?







      c# file-io






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Jun 17 '14 at 7:19









      bluish

      13.9k1693147




      13.9k1693147










      asked May 6 '10 at 13:15









      BrettBrett

      82321224




      82321224
























          10 Answers
          10






          active

          oldest

          votes


















          99














          The File.Create method creates the file and opens a FileStream on the file. So your file is already open. You don't really need the file.Create method at all:



          string filePath = @"c:somefilename.txt";
          using (StreamWriter sw = new StreamWriter(filePath, true))
          {
          //write to the file
          }


          The boolean in the StreamWriter constructor will cause the contents to be appended if the file exists.






          share|improve this answer


























          • i tried the above code but i am getting the same error when the file is created and when it tries to write in to the file it shows file is being used by other process.

            – Anmol Rathod
            Jul 15 '18 at 20:58











          • @AnmolRathod go sure that you don't use File.Create() method! The snippet above already creates the file!

            – Daniel Eisenreich
            Aug 15 '18 at 13:25



















          126














              File.Create(FilePath).Close();
          File.WriteAllText(FileText);


          I want to update this answer to say that this is not really the most efficient way to write all text. You should only use this code if you need something quick and dirty.



          I was a young programmer when I answered this question, and back then I thought I was some kind of genius for coming up with this answer.






          share|improve this answer





















          • 3





            this was useful.

            – Siva
            Oct 1 '11 at 16:03






          • 4





            I love how all the other answers were just way too complicated. People don't realize that there is a simpler answer to every problem.

            – Carsen Daniel Yates
            Nov 23 '11 at 1:08






          • 13





            The downside to this code is that it unnecessarily opens the file twice. Also, it isn't really necessary to check whether the file exists at all, as the FileStream constructor will automatically create it for you if it does not exist, unless you explicitly tell it not to do that.

            – reirab
            Aug 9 '13 at 14:02






          • 2





            @reirab This is completely relative. I need to check if the file exists and if it does, delete it and create it again, so this answer is preferred in my case.

            – makoshichi
            Apr 13 '16 at 13:54






          • 1





            @S.O. Then you have a different problem than the OP, just a related one. Also, in your case, you can still just use the FileStream(string, FileMode) constructor and pass it FileMode.Create, which will overwrite any existing file. Still no need to open the file twice. Also, this answer was edited after I posted my original comment.

            – reirab
            Apr 13 '16 at 14:23





















          23














          When creating a text file you can use the following code:



          System.IO.File.WriteAllText("c:test.txt", "all of your content here");


          Using the code from your comment. The file(stream) you created must be closed. File.Create return the filestream to the just created file.:



          string filePath = "filepath here";
          if (!System.IO.File.Exists(filePath))
          {
          System.IO.FileStream f = System.IO.File.Create(filePath);
          f.Close();
          }
          using (System.IO.StreamWriter sw = System.IO.File.AppendText(filePath))
          {
          //write my text
          }





          share|improve this answer


























          • I don't seem to have a close option. Here's the code: string filePath = string.Format(@"{0}M{1}.dat", ConfigurationManager.AppSettings["DirectoryPath"], costCentre); if (!File.Exists(filePath)) { File.Create(filePath); } using (StreamWriter sw = File.AppendText(filePath)) { //write my text }

            – Brett
            May 6 '10 at 13:23











          • File.Create returns FileStream and that has Close()

            – Null Head
            Sep 7 '15 at 20:49



















          16














          FileStream fs= File.Create(ConfigurationManager.AppSettings["file"]);
          fs.Close();





          share|improve this answer





















          • 5





            Welcome to Stackoverflow. You should at least write short description to describe your answer/solution.

            – Paresh Mayani
            Mar 17 '14 at 19:24











          • This was only thing that worked!! <3

            – Chris Emerson
            Sep 22 '16 at 12:19



















          9














          File.Create returns a FileStream. You need to close that when you have written to the file:



          using (FileStream fs = File.Create(path, 1024)) 
          {
          Byte info = new UTF8Encoding(true).GetBytes("This is some text in the file.");
          // Add some information to the file.
          fs.Write(info, 0, info.Length);
          }


          You can use using for automatically closing the file.






          share|improve this answer
























          • Though the OP is trying to open a StreamWriter as can be inferred from his use of File.AppendText.

            – binki
            Nov 29 '16 at 18:55



















          8














          I updated your question with the code snippet. After proper indenting, it is immediately clear what the problem is: you use File.Create() but don't close the FileStream that it returns.



          Doing it that way is unnecessary, StreamWriter already allows appending to an existing file and creating a new file if it doesn't yet exist. Like this:



            string filePath = string.Format(@"{0}M{1}.dat", ConfigurationManager.AppSettings["DirectoryPath"], costCentre); 
          using (StreamWriter sw = new StreamWriter(filePath, true)) {
          //write my text
          }


          Which uses this StreamWriter constructor.






          share|improve this answer

































            1














            This question has already been answered, but here is a real world solution that
            checks if the directory exists and adds a number to the end if the text file
            exists. I use this for creating daily log files on a Windows service I wrote. I
            hope this helps someone.



            // How to create a log file with a sortable date and add numbering to it if it already exists.
            public void CreateLogFile()
            {
            // filePath usually comes from the App.config file. I've written the value explicitly here for demo purposes.
            var filePath = "C:\Logs";

            // Append a backslash if one is not present at the end of the file path.
            if (!filePath.EndsWith("\"))
            {
            filePath += "\";
            }

            // Create the path if it doesn't exist.
            if (!Directory.Exists(filePath))
            {
            Directory.CreateDirectory(filePath);
            }

            // Create the file name with a calendar sortable date on the end.
            var now = DateTime.Now;
            filePath += string.Format("Daily Log [{0}-{1}-{2}].txt", now.Year, now.Month, now.Day);

            // Check if the file that is about to be created already exists. If so, append a number to the end.
            if (File.Exists(filePath))
            {
            var counter = 1;
            filePath = filePath.Replace(".txt", " (" + counter + ").txt");
            while (File.Exists(filePath))
            {
            filePath = filePath.Replace("(" + counter + ").txt", "(" + (counter + 1) + ").txt");
            counter++;
            }
            }

            // Note that after the file is created, the file stream is still open. It needs to be closed
            // once it is created if other methods need to access it.
            using (var file = File.Create(filePath))
            {
            file.Close();
            }
            }





            share|improve this answer































              1














              I know this is an old question, but I just want to throw this out there that you can still use File.Create("filename")", just add .Dispose() to it.



              File.Create("filename").Dispose();



              This way it creates and closes the file for the next process to use it.






              share|improve this answer
























              • File.Create(FilePath).Close(); from the answer above has this.Dispose(true); GC.SuppressFinalize((object) this); in its implementation.

                – Ghukas
                2 days ago



















              0














              Finally, I think I know the reason for this exception. You might be running this code snippet in multiple threads.






              share|improve this answer































                -1














                Try this: It works in any case, if the file doesn't exists, it will create it and then write to it. And if already exists, no problem it will open and write to it :



                using (FileStream fs= new FileStream(@"File.txt",FileMode.Create,FileAccess.ReadWrite))
                {
                fs.close();
                }
                using (StreamWriter sw = new StreamWriter(@"File.txt"))
                {
                sw.WriteLine("bla bla bla");
                sw.Close();
                }





                share|improve this answer





















                • 1





                  using will close file by call Dispose. In your sample file was closed twice

                  – Valentine Zakharenko
                  Sep 20 '16 at 4:24











                Your Answer






                StackExchange.ifUsing("editor", function () {
                StackExchange.using("externalEditor", function () {
                StackExchange.using("snippets", function () {
                StackExchange.snippets.init();
                });
                });
                }, "code-snippets");

                StackExchange.ready(function() {
                var channelOptions = {
                tags: "".split(" "),
                id: "1"
                };
                initTagRenderer("".split(" "), "".split(" "), channelOptions);

                StackExchange.using("externalEditor", function() {
                // Have to fire editor after snippets, if snippets enabled
                if (StackExchange.settings.snippets.snippetsEnabled) {
                StackExchange.using("snippets", function() {
                createEditor();
                });
                }
                else {
                createEditor();
                }
                });

                function createEditor() {
                StackExchange.prepareEditor({
                heartbeatType: 'answer',
                autoActivateHeartbeat: false,
                convertImagesToLinks: true,
                noModals: true,
                showLowRepImageUploadWarning: true,
                reputationToPostImages: 10,
                bindNavPrevention: true,
                postfix: "",
                imageUploader: {
                brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                allowUrls: true
                },
                onDemand: true,
                discardSelector: ".discard-answer"
                ,immediatelyShowMarkdownHelp:true
                });


                }
                });














                draft saved

                draft discarded


















                StackExchange.ready(
                function () {
                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f2781357%2ffile-being-used-by-another-process-after-using-file-create%23new-answer', 'question_page');
                }
                );

                Post as a guest















                Required, but never shown

























                10 Answers
                10






                active

                oldest

                votes








                10 Answers
                10






                active

                oldest

                votes









                active

                oldest

                votes






                active

                oldest

                votes









                99














                The File.Create method creates the file and opens a FileStream on the file. So your file is already open. You don't really need the file.Create method at all:



                string filePath = @"c:somefilename.txt";
                using (StreamWriter sw = new StreamWriter(filePath, true))
                {
                //write to the file
                }


                The boolean in the StreamWriter constructor will cause the contents to be appended if the file exists.






                share|improve this answer


























                • i tried the above code but i am getting the same error when the file is created and when it tries to write in to the file it shows file is being used by other process.

                  – Anmol Rathod
                  Jul 15 '18 at 20:58











                • @AnmolRathod go sure that you don't use File.Create() method! The snippet above already creates the file!

                  – Daniel Eisenreich
                  Aug 15 '18 at 13:25
















                99














                The File.Create method creates the file and opens a FileStream on the file. So your file is already open. You don't really need the file.Create method at all:



                string filePath = @"c:somefilename.txt";
                using (StreamWriter sw = new StreamWriter(filePath, true))
                {
                //write to the file
                }


                The boolean in the StreamWriter constructor will cause the contents to be appended if the file exists.






                share|improve this answer


























                • i tried the above code but i am getting the same error when the file is created and when it tries to write in to the file it shows file is being used by other process.

                  – Anmol Rathod
                  Jul 15 '18 at 20:58











                • @AnmolRathod go sure that you don't use File.Create() method! The snippet above already creates the file!

                  – Daniel Eisenreich
                  Aug 15 '18 at 13:25














                99












                99








                99







                The File.Create method creates the file and opens a FileStream on the file. So your file is already open. You don't really need the file.Create method at all:



                string filePath = @"c:somefilename.txt";
                using (StreamWriter sw = new StreamWriter(filePath, true))
                {
                //write to the file
                }


                The boolean in the StreamWriter constructor will cause the contents to be appended if the file exists.






                share|improve this answer















                The File.Create method creates the file and opens a FileStream on the file. So your file is already open. You don't really need the file.Create method at all:



                string filePath = @"c:somefilename.txt";
                using (StreamWriter sw = new StreamWriter(filePath, true))
                {
                //write to the file
                }


                The boolean in the StreamWriter constructor will cause the contents to be appended if the file exists.







                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Jun 17 '14 at 7:19









                bluish

                13.9k1693147




                13.9k1693147










                answered May 6 '10 at 13:32









                Chris DunawayChris Dunaway

                8,53512742




                8,53512742













                • i tried the above code but i am getting the same error when the file is created and when it tries to write in to the file it shows file is being used by other process.

                  – Anmol Rathod
                  Jul 15 '18 at 20:58











                • @AnmolRathod go sure that you don't use File.Create() method! The snippet above already creates the file!

                  – Daniel Eisenreich
                  Aug 15 '18 at 13:25



















                • i tried the above code but i am getting the same error when the file is created and when it tries to write in to the file it shows file is being used by other process.

                  – Anmol Rathod
                  Jul 15 '18 at 20:58











                • @AnmolRathod go sure that you don't use File.Create() method! The snippet above already creates the file!

                  – Daniel Eisenreich
                  Aug 15 '18 at 13:25

















                i tried the above code but i am getting the same error when the file is created and when it tries to write in to the file it shows file is being used by other process.

                – Anmol Rathod
                Jul 15 '18 at 20:58





                i tried the above code but i am getting the same error when the file is created and when it tries to write in to the file it shows file is being used by other process.

                – Anmol Rathod
                Jul 15 '18 at 20:58













                @AnmolRathod go sure that you don't use File.Create() method! The snippet above already creates the file!

                – Daniel Eisenreich
                Aug 15 '18 at 13:25





                @AnmolRathod go sure that you don't use File.Create() method! The snippet above already creates the file!

                – Daniel Eisenreich
                Aug 15 '18 at 13:25













                126














                    File.Create(FilePath).Close();
                File.WriteAllText(FileText);


                I want to update this answer to say that this is not really the most efficient way to write all text. You should only use this code if you need something quick and dirty.



                I was a young programmer when I answered this question, and back then I thought I was some kind of genius for coming up with this answer.






                share|improve this answer





















                • 3





                  this was useful.

                  – Siva
                  Oct 1 '11 at 16:03






                • 4





                  I love how all the other answers were just way too complicated. People don't realize that there is a simpler answer to every problem.

                  – Carsen Daniel Yates
                  Nov 23 '11 at 1:08






                • 13





                  The downside to this code is that it unnecessarily opens the file twice. Also, it isn't really necessary to check whether the file exists at all, as the FileStream constructor will automatically create it for you if it does not exist, unless you explicitly tell it not to do that.

                  – reirab
                  Aug 9 '13 at 14:02






                • 2





                  @reirab This is completely relative. I need to check if the file exists and if it does, delete it and create it again, so this answer is preferred in my case.

                  – makoshichi
                  Apr 13 '16 at 13:54






                • 1





                  @S.O. Then you have a different problem than the OP, just a related one. Also, in your case, you can still just use the FileStream(string, FileMode) constructor and pass it FileMode.Create, which will overwrite any existing file. Still no need to open the file twice. Also, this answer was edited after I posted my original comment.

                  – reirab
                  Apr 13 '16 at 14:23


















                126














                    File.Create(FilePath).Close();
                File.WriteAllText(FileText);


                I want to update this answer to say that this is not really the most efficient way to write all text. You should only use this code if you need something quick and dirty.



                I was a young programmer when I answered this question, and back then I thought I was some kind of genius for coming up with this answer.






                share|improve this answer





















                • 3





                  this was useful.

                  – Siva
                  Oct 1 '11 at 16:03






                • 4





                  I love how all the other answers were just way too complicated. People don't realize that there is a simpler answer to every problem.

                  – Carsen Daniel Yates
                  Nov 23 '11 at 1:08






                • 13





                  The downside to this code is that it unnecessarily opens the file twice. Also, it isn't really necessary to check whether the file exists at all, as the FileStream constructor will automatically create it for you if it does not exist, unless you explicitly tell it not to do that.

                  – reirab
                  Aug 9 '13 at 14:02






                • 2





                  @reirab This is completely relative. I need to check if the file exists and if it does, delete it and create it again, so this answer is preferred in my case.

                  – makoshichi
                  Apr 13 '16 at 13:54






                • 1





                  @S.O. Then you have a different problem than the OP, just a related one. Also, in your case, you can still just use the FileStream(string, FileMode) constructor and pass it FileMode.Create, which will overwrite any existing file. Still no need to open the file twice. Also, this answer was edited after I posted my original comment.

                  – reirab
                  Apr 13 '16 at 14:23
















                126












                126








                126







                    File.Create(FilePath).Close();
                File.WriteAllText(FileText);


                I want to update this answer to say that this is not really the most efficient way to write all text. You should only use this code if you need something quick and dirty.



                I was a young programmer when I answered this question, and back then I thought I was some kind of genius for coming up with this answer.






                share|improve this answer















                    File.Create(FilePath).Close();
                File.WriteAllText(FileText);


                I want to update this answer to say that this is not really the most efficient way to write all text. You should only use this code if you need something quick and dirty.



                I was a young programmer when I answered this question, and back then I thought I was some kind of genius for coming up with this answer.







                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Nov 24 '18 at 3:45

























                answered Jul 27 '11 at 19:14









                Carsen Daniel YatesCarsen Daniel Yates

                1,4951915




                1,4951915








                • 3





                  this was useful.

                  – Siva
                  Oct 1 '11 at 16:03






                • 4





                  I love how all the other answers were just way too complicated. People don't realize that there is a simpler answer to every problem.

                  – Carsen Daniel Yates
                  Nov 23 '11 at 1:08






                • 13





                  The downside to this code is that it unnecessarily opens the file twice. Also, it isn't really necessary to check whether the file exists at all, as the FileStream constructor will automatically create it for you if it does not exist, unless you explicitly tell it not to do that.

                  – reirab
                  Aug 9 '13 at 14:02






                • 2





                  @reirab This is completely relative. I need to check if the file exists and if it does, delete it and create it again, so this answer is preferred in my case.

                  – makoshichi
                  Apr 13 '16 at 13:54






                • 1





                  @S.O. Then you have a different problem than the OP, just a related one. Also, in your case, you can still just use the FileStream(string, FileMode) constructor and pass it FileMode.Create, which will overwrite any existing file. Still no need to open the file twice. Also, this answer was edited after I posted my original comment.

                  – reirab
                  Apr 13 '16 at 14:23
















                • 3





                  this was useful.

                  – Siva
                  Oct 1 '11 at 16:03






                • 4





                  I love how all the other answers were just way too complicated. People don't realize that there is a simpler answer to every problem.

                  – Carsen Daniel Yates
                  Nov 23 '11 at 1:08






                • 13





                  The downside to this code is that it unnecessarily opens the file twice. Also, it isn't really necessary to check whether the file exists at all, as the FileStream constructor will automatically create it for you if it does not exist, unless you explicitly tell it not to do that.

                  – reirab
                  Aug 9 '13 at 14:02






                • 2





                  @reirab This is completely relative. I need to check if the file exists and if it does, delete it and create it again, so this answer is preferred in my case.

                  – makoshichi
                  Apr 13 '16 at 13:54






                • 1





                  @S.O. Then you have a different problem than the OP, just a related one. Also, in your case, you can still just use the FileStream(string, FileMode) constructor and pass it FileMode.Create, which will overwrite any existing file. Still no need to open the file twice. Also, this answer was edited after I posted my original comment.

                  – reirab
                  Apr 13 '16 at 14:23










                3




                3





                this was useful.

                – Siva
                Oct 1 '11 at 16:03





                this was useful.

                – Siva
                Oct 1 '11 at 16:03




                4




                4





                I love how all the other answers were just way too complicated. People don't realize that there is a simpler answer to every problem.

                – Carsen Daniel Yates
                Nov 23 '11 at 1:08





                I love how all the other answers were just way too complicated. People don't realize that there is a simpler answer to every problem.

                – Carsen Daniel Yates
                Nov 23 '11 at 1:08




                13




                13





                The downside to this code is that it unnecessarily opens the file twice. Also, it isn't really necessary to check whether the file exists at all, as the FileStream constructor will automatically create it for you if it does not exist, unless you explicitly tell it not to do that.

                – reirab
                Aug 9 '13 at 14:02





                The downside to this code is that it unnecessarily opens the file twice. Also, it isn't really necessary to check whether the file exists at all, as the FileStream constructor will automatically create it for you if it does not exist, unless you explicitly tell it not to do that.

                – reirab
                Aug 9 '13 at 14:02




                2




                2





                @reirab This is completely relative. I need to check if the file exists and if it does, delete it and create it again, so this answer is preferred in my case.

                – makoshichi
                Apr 13 '16 at 13:54





                @reirab This is completely relative. I need to check if the file exists and if it does, delete it and create it again, so this answer is preferred in my case.

                – makoshichi
                Apr 13 '16 at 13:54




                1




                1





                @S.O. Then you have a different problem than the OP, just a related one. Also, in your case, you can still just use the FileStream(string, FileMode) constructor and pass it FileMode.Create, which will overwrite any existing file. Still no need to open the file twice. Also, this answer was edited after I posted my original comment.

                – reirab
                Apr 13 '16 at 14:23







                @S.O. Then you have a different problem than the OP, just a related one. Also, in your case, you can still just use the FileStream(string, FileMode) constructor and pass it FileMode.Create, which will overwrite any existing file. Still no need to open the file twice. Also, this answer was edited after I posted my original comment.

                – reirab
                Apr 13 '16 at 14:23













                23














                When creating a text file you can use the following code:



                System.IO.File.WriteAllText("c:test.txt", "all of your content here");


                Using the code from your comment. The file(stream) you created must be closed. File.Create return the filestream to the just created file.:



                string filePath = "filepath here";
                if (!System.IO.File.Exists(filePath))
                {
                System.IO.FileStream f = System.IO.File.Create(filePath);
                f.Close();
                }
                using (System.IO.StreamWriter sw = System.IO.File.AppendText(filePath))
                {
                //write my text
                }





                share|improve this answer


























                • I don't seem to have a close option. Here's the code: string filePath = string.Format(@"{0}M{1}.dat", ConfigurationManager.AppSettings["DirectoryPath"], costCentre); if (!File.Exists(filePath)) { File.Create(filePath); } using (StreamWriter sw = File.AppendText(filePath)) { //write my text }

                  – Brett
                  May 6 '10 at 13:23











                • File.Create returns FileStream and that has Close()

                  – Null Head
                  Sep 7 '15 at 20:49
















                23














                When creating a text file you can use the following code:



                System.IO.File.WriteAllText("c:test.txt", "all of your content here");


                Using the code from your comment. The file(stream) you created must be closed. File.Create return the filestream to the just created file.:



                string filePath = "filepath here";
                if (!System.IO.File.Exists(filePath))
                {
                System.IO.FileStream f = System.IO.File.Create(filePath);
                f.Close();
                }
                using (System.IO.StreamWriter sw = System.IO.File.AppendText(filePath))
                {
                //write my text
                }





                share|improve this answer


























                • I don't seem to have a close option. Here's the code: string filePath = string.Format(@"{0}M{1}.dat", ConfigurationManager.AppSettings["DirectoryPath"], costCentre); if (!File.Exists(filePath)) { File.Create(filePath); } using (StreamWriter sw = File.AppendText(filePath)) { //write my text }

                  – Brett
                  May 6 '10 at 13:23











                • File.Create returns FileStream and that has Close()

                  – Null Head
                  Sep 7 '15 at 20:49














                23












                23








                23







                When creating a text file you can use the following code:



                System.IO.File.WriteAllText("c:test.txt", "all of your content here");


                Using the code from your comment. The file(stream) you created must be closed. File.Create return the filestream to the just created file.:



                string filePath = "filepath here";
                if (!System.IO.File.Exists(filePath))
                {
                System.IO.FileStream f = System.IO.File.Create(filePath);
                f.Close();
                }
                using (System.IO.StreamWriter sw = System.IO.File.AppendText(filePath))
                {
                //write my text
                }





                share|improve this answer















                When creating a text file you can use the following code:



                System.IO.File.WriteAllText("c:test.txt", "all of your content here");


                Using the code from your comment. The file(stream) you created must be closed. File.Create return the filestream to the just created file.:



                string filePath = "filepath here";
                if (!System.IO.File.Exists(filePath))
                {
                System.IO.FileStream f = System.IO.File.Create(filePath);
                f.Close();
                }
                using (System.IO.StreamWriter sw = System.IO.File.AppendText(filePath))
                {
                //write my text
                }






                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Apr 25 '13 at 6:00

























                answered May 6 '10 at 13:20









                Ralf de KleineRalf de Kleine

                8,97623073




                8,97623073













                • I don't seem to have a close option. Here's the code: string filePath = string.Format(@"{0}M{1}.dat", ConfigurationManager.AppSettings["DirectoryPath"], costCentre); if (!File.Exists(filePath)) { File.Create(filePath); } using (StreamWriter sw = File.AppendText(filePath)) { //write my text }

                  – Brett
                  May 6 '10 at 13:23











                • File.Create returns FileStream and that has Close()

                  – Null Head
                  Sep 7 '15 at 20:49



















                • I don't seem to have a close option. Here's the code: string filePath = string.Format(@"{0}M{1}.dat", ConfigurationManager.AppSettings["DirectoryPath"], costCentre); if (!File.Exists(filePath)) { File.Create(filePath); } using (StreamWriter sw = File.AppendText(filePath)) { //write my text }

                  – Brett
                  May 6 '10 at 13:23











                • File.Create returns FileStream and that has Close()

                  – Null Head
                  Sep 7 '15 at 20:49

















                I don't seem to have a close option. Here's the code: string filePath = string.Format(@"{0}M{1}.dat", ConfigurationManager.AppSettings["DirectoryPath"], costCentre); if (!File.Exists(filePath)) { File.Create(filePath); } using (StreamWriter sw = File.AppendText(filePath)) { //write my text }

                – Brett
                May 6 '10 at 13:23





                I don't seem to have a close option. Here's the code: string filePath = string.Format(@"{0}M{1}.dat", ConfigurationManager.AppSettings["DirectoryPath"], costCentre); if (!File.Exists(filePath)) { File.Create(filePath); } using (StreamWriter sw = File.AppendText(filePath)) { //write my text }

                – Brett
                May 6 '10 at 13:23













                File.Create returns FileStream and that has Close()

                – Null Head
                Sep 7 '15 at 20:49





                File.Create returns FileStream and that has Close()

                – Null Head
                Sep 7 '15 at 20:49











                16














                FileStream fs= File.Create(ConfigurationManager.AppSettings["file"]);
                fs.Close();





                share|improve this answer





















                • 5





                  Welcome to Stackoverflow. You should at least write short description to describe your answer/solution.

                  – Paresh Mayani
                  Mar 17 '14 at 19:24











                • This was only thing that worked!! <3

                  – Chris Emerson
                  Sep 22 '16 at 12:19
















                16














                FileStream fs= File.Create(ConfigurationManager.AppSettings["file"]);
                fs.Close();





                share|improve this answer





















                • 5





                  Welcome to Stackoverflow. You should at least write short description to describe your answer/solution.

                  – Paresh Mayani
                  Mar 17 '14 at 19:24











                • This was only thing that worked!! <3

                  – Chris Emerson
                  Sep 22 '16 at 12:19














                16












                16








                16







                FileStream fs= File.Create(ConfigurationManager.AppSettings["file"]);
                fs.Close();





                share|improve this answer















                FileStream fs= File.Create(ConfigurationManager.AppSettings["file"]);
                fs.Close();






                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Mar 17 '14 at 19:24









                Paresh Mayani

                96.4k62222279




                96.4k62222279










                answered Mar 17 '14 at 19:22









                user3430377user3430377

                16912




                16912








                • 5





                  Welcome to Stackoverflow. You should at least write short description to describe your answer/solution.

                  – Paresh Mayani
                  Mar 17 '14 at 19:24











                • This was only thing that worked!! <3

                  – Chris Emerson
                  Sep 22 '16 at 12:19














                • 5





                  Welcome to Stackoverflow. You should at least write short description to describe your answer/solution.

                  – Paresh Mayani
                  Mar 17 '14 at 19:24











                • This was only thing that worked!! <3

                  – Chris Emerson
                  Sep 22 '16 at 12:19








                5




                5





                Welcome to Stackoverflow. You should at least write short description to describe your answer/solution.

                – Paresh Mayani
                Mar 17 '14 at 19:24





                Welcome to Stackoverflow. You should at least write short description to describe your answer/solution.

                – Paresh Mayani
                Mar 17 '14 at 19:24













                This was only thing that worked!! <3

                – Chris Emerson
                Sep 22 '16 at 12:19





                This was only thing that worked!! <3

                – Chris Emerson
                Sep 22 '16 at 12:19











                9














                File.Create returns a FileStream. You need to close that when you have written to the file:



                using (FileStream fs = File.Create(path, 1024)) 
                {
                Byte info = new UTF8Encoding(true).GetBytes("This is some text in the file.");
                // Add some information to the file.
                fs.Write(info, 0, info.Length);
                }


                You can use using for automatically closing the file.






                share|improve this answer
























                • Though the OP is trying to open a StreamWriter as can be inferred from his use of File.AppendText.

                  – binki
                  Nov 29 '16 at 18:55
















                9














                File.Create returns a FileStream. You need to close that when you have written to the file:



                using (FileStream fs = File.Create(path, 1024)) 
                {
                Byte info = new UTF8Encoding(true).GetBytes("This is some text in the file.");
                // Add some information to the file.
                fs.Write(info, 0, info.Length);
                }


                You can use using for automatically closing the file.






                share|improve this answer
























                • Though the OP is trying to open a StreamWriter as can be inferred from his use of File.AppendText.

                  – binki
                  Nov 29 '16 at 18:55














                9












                9








                9







                File.Create returns a FileStream. You need to close that when you have written to the file:



                using (FileStream fs = File.Create(path, 1024)) 
                {
                Byte info = new UTF8Encoding(true).GetBytes("This is some text in the file.");
                // Add some information to the file.
                fs.Write(info, 0, info.Length);
                }


                You can use using for automatically closing the file.






                share|improve this answer













                File.Create returns a FileStream. You need to close that when you have written to the file:



                using (FileStream fs = File.Create(path, 1024)) 
                {
                Byte info = new UTF8Encoding(true).GetBytes("This is some text in the file.");
                // Add some information to the file.
                fs.Write(info, 0, info.Length);
                }


                You can use using for automatically closing the file.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered May 6 '10 at 13:32









                kimtiedekimtiede

                1828




                1828













                • Though the OP is trying to open a StreamWriter as can be inferred from his use of File.AppendText.

                  – binki
                  Nov 29 '16 at 18:55



















                • Though the OP is trying to open a StreamWriter as can be inferred from his use of File.AppendText.

                  – binki
                  Nov 29 '16 at 18:55

















                Though the OP is trying to open a StreamWriter as can be inferred from his use of File.AppendText.

                – binki
                Nov 29 '16 at 18:55





                Though the OP is trying to open a StreamWriter as can be inferred from his use of File.AppendText.

                – binki
                Nov 29 '16 at 18:55











                8














                I updated your question with the code snippet. After proper indenting, it is immediately clear what the problem is: you use File.Create() but don't close the FileStream that it returns.



                Doing it that way is unnecessary, StreamWriter already allows appending to an existing file and creating a new file if it doesn't yet exist. Like this:



                  string filePath = string.Format(@"{0}M{1}.dat", ConfigurationManager.AppSettings["DirectoryPath"], costCentre); 
                using (StreamWriter sw = new StreamWriter(filePath, true)) {
                //write my text
                }


                Which uses this StreamWriter constructor.






                share|improve this answer






























                  8














                  I updated your question with the code snippet. After proper indenting, it is immediately clear what the problem is: you use File.Create() but don't close the FileStream that it returns.



                  Doing it that way is unnecessary, StreamWriter already allows appending to an existing file and creating a new file if it doesn't yet exist. Like this:



                    string filePath = string.Format(@"{0}M{1}.dat", ConfigurationManager.AppSettings["DirectoryPath"], costCentre); 
                  using (StreamWriter sw = new StreamWriter(filePath, true)) {
                  //write my text
                  }


                  Which uses this StreamWriter constructor.






                  share|improve this answer




























                    8












                    8








                    8







                    I updated your question with the code snippet. After proper indenting, it is immediately clear what the problem is: you use File.Create() but don't close the FileStream that it returns.



                    Doing it that way is unnecessary, StreamWriter already allows appending to an existing file and creating a new file if it doesn't yet exist. Like this:



                      string filePath = string.Format(@"{0}M{1}.dat", ConfigurationManager.AppSettings["DirectoryPath"], costCentre); 
                    using (StreamWriter sw = new StreamWriter(filePath, true)) {
                    //write my text
                    }


                    Which uses this StreamWriter constructor.






                    share|improve this answer















                    I updated your question with the code snippet. After proper indenting, it is immediately clear what the problem is: you use File.Create() but don't close the FileStream that it returns.



                    Doing it that way is unnecessary, StreamWriter already allows appending to an existing file and creating a new file if it doesn't yet exist. Like this:



                      string filePath = string.Format(@"{0}M{1}.dat", ConfigurationManager.AppSettings["DirectoryPath"], costCentre); 
                    using (StreamWriter sw = new StreamWriter(filePath, true)) {
                    //write my text
                    }


                    Which uses this StreamWriter constructor.







                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Oct 28 '15 at 9:35









                    Hossein Narimani Rad

                    20.5k116296




                    20.5k116296










                    answered May 6 '10 at 15:13









                    Hans PassantHans Passant

                    787k10612982072




                    787k10612982072























                        1














                        This question has already been answered, but here is a real world solution that
                        checks if the directory exists and adds a number to the end if the text file
                        exists. I use this for creating daily log files on a Windows service I wrote. I
                        hope this helps someone.



                        // How to create a log file with a sortable date and add numbering to it if it already exists.
                        public void CreateLogFile()
                        {
                        // filePath usually comes from the App.config file. I've written the value explicitly here for demo purposes.
                        var filePath = "C:\Logs";

                        // Append a backslash if one is not present at the end of the file path.
                        if (!filePath.EndsWith("\"))
                        {
                        filePath += "\";
                        }

                        // Create the path if it doesn't exist.
                        if (!Directory.Exists(filePath))
                        {
                        Directory.CreateDirectory(filePath);
                        }

                        // Create the file name with a calendar sortable date on the end.
                        var now = DateTime.Now;
                        filePath += string.Format("Daily Log [{0}-{1}-{2}].txt", now.Year, now.Month, now.Day);

                        // Check if the file that is about to be created already exists. If so, append a number to the end.
                        if (File.Exists(filePath))
                        {
                        var counter = 1;
                        filePath = filePath.Replace(".txt", " (" + counter + ").txt");
                        while (File.Exists(filePath))
                        {
                        filePath = filePath.Replace("(" + counter + ").txt", "(" + (counter + 1) + ").txt");
                        counter++;
                        }
                        }

                        // Note that after the file is created, the file stream is still open. It needs to be closed
                        // once it is created if other methods need to access it.
                        using (var file = File.Create(filePath))
                        {
                        file.Close();
                        }
                        }





                        share|improve this answer




























                          1














                          This question has already been answered, but here is a real world solution that
                          checks if the directory exists and adds a number to the end if the text file
                          exists. I use this for creating daily log files on a Windows service I wrote. I
                          hope this helps someone.



                          // How to create a log file with a sortable date and add numbering to it if it already exists.
                          public void CreateLogFile()
                          {
                          // filePath usually comes from the App.config file. I've written the value explicitly here for demo purposes.
                          var filePath = "C:\Logs";

                          // Append a backslash if one is not present at the end of the file path.
                          if (!filePath.EndsWith("\"))
                          {
                          filePath += "\";
                          }

                          // Create the path if it doesn't exist.
                          if (!Directory.Exists(filePath))
                          {
                          Directory.CreateDirectory(filePath);
                          }

                          // Create the file name with a calendar sortable date on the end.
                          var now = DateTime.Now;
                          filePath += string.Format("Daily Log [{0}-{1}-{2}].txt", now.Year, now.Month, now.Day);

                          // Check if the file that is about to be created already exists. If so, append a number to the end.
                          if (File.Exists(filePath))
                          {
                          var counter = 1;
                          filePath = filePath.Replace(".txt", " (" + counter + ").txt");
                          while (File.Exists(filePath))
                          {
                          filePath = filePath.Replace("(" + counter + ").txt", "(" + (counter + 1) + ").txt");
                          counter++;
                          }
                          }

                          // Note that after the file is created, the file stream is still open. It needs to be closed
                          // once it is created if other methods need to access it.
                          using (var file = File.Create(filePath))
                          {
                          file.Close();
                          }
                          }





                          share|improve this answer


























                            1












                            1








                            1







                            This question has already been answered, but here is a real world solution that
                            checks if the directory exists and adds a number to the end if the text file
                            exists. I use this for creating daily log files on a Windows service I wrote. I
                            hope this helps someone.



                            // How to create a log file with a sortable date and add numbering to it if it already exists.
                            public void CreateLogFile()
                            {
                            // filePath usually comes from the App.config file. I've written the value explicitly here for demo purposes.
                            var filePath = "C:\Logs";

                            // Append a backslash if one is not present at the end of the file path.
                            if (!filePath.EndsWith("\"))
                            {
                            filePath += "\";
                            }

                            // Create the path if it doesn't exist.
                            if (!Directory.Exists(filePath))
                            {
                            Directory.CreateDirectory(filePath);
                            }

                            // Create the file name with a calendar sortable date on the end.
                            var now = DateTime.Now;
                            filePath += string.Format("Daily Log [{0}-{1}-{2}].txt", now.Year, now.Month, now.Day);

                            // Check if the file that is about to be created already exists. If so, append a number to the end.
                            if (File.Exists(filePath))
                            {
                            var counter = 1;
                            filePath = filePath.Replace(".txt", " (" + counter + ").txt");
                            while (File.Exists(filePath))
                            {
                            filePath = filePath.Replace("(" + counter + ").txt", "(" + (counter + 1) + ").txt");
                            counter++;
                            }
                            }

                            // Note that after the file is created, the file stream is still open. It needs to be closed
                            // once it is created if other methods need to access it.
                            using (var file = File.Create(filePath))
                            {
                            file.Close();
                            }
                            }





                            share|improve this answer













                            This question has already been answered, but here is a real world solution that
                            checks if the directory exists and adds a number to the end if the text file
                            exists. I use this for creating daily log files on a Windows service I wrote. I
                            hope this helps someone.



                            // How to create a log file with a sortable date and add numbering to it if it already exists.
                            public void CreateLogFile()
                            {
                            // filePath usually comes from the App.config file. I've written the value explicitly here for demo purposes.
                            var filePath = "C:\Logs";

                            // Append a backslash if one is not present at the end of the file path.
                            if (!filePath.EndsWith("\"))
                            {
                            filePath += "\";
                            }

                            // Create the path if it doesn't exist.
                            if (!Directory.Exists(filePath))
                            {
                            Directory.CreateDirectory(filePath);
                            }

                            // Create the file name with a calendar sortable date on the end.
                            var now = DateTime.Now;
                            filePath += string.Format("Daily Log [{0}-{1}-{2}].txt", now.Year, now.Month, now.Day);

                            // Check if the file that is about to be created already exists. If so, append a number to the end.
                            if (File.Exists(filePath))
                            {
                            var counter = 1;
                            filePath = filePath.Replace(".txt", " (" + counter + ").txt");
                            while (File.Exists(filePath))
                            {
                            filePath = filePath.Replace("(" + counter + ").txt", "(" + (counter + 1) + ").txt");
                            counter++;
                            }
                            }

                            // Note that after the file is created, the file stream is still open. It needs to be closed
                            // once it is created if other methods need to access it.
                            using (var file = File.Create(filePath))
                            {
                            file.Close();
                            }
                            }






                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Oct 12 '11 at 22:49









                            HalcyonHalcyon

                            7,488145481




                            7,488145481























                                1














                                I know this is an old question, but I just want to throw this out there that you can still use File.Create("filename")", just add .Dispose() to it.



                                File.Create("filename").Dispose();



                                This way it creates and closes the file for the next process to use it.






                                share|improve this answer
























                                • File.Create(FilePath).Close(); from the answer above has this.Dispose(true); GC.SuppressFinalize((object) this); in its implementation.

                                  – Ghukas
                                  2 days ago
















                                1














                                I know this is an old question, but I just want to throw this out there that you can still use File.Create("filename")", just add .Dispose() to it.



                                File.Create("filename").Dispose();



                                This way it creates and closes the file for the next process to use it.






                                share|improve this answer
























                                • File.Create(FilePath).Close(); from the answer above has this.Dispose(true); GC.SuppressFinalize((object) this); in its implementation.

                                  – Ghukas
                                  2 days ago














                                1












                                1








                                1







                                I know this is an old question, but I just want to throw this out there that you can still use File.Create("filename")", just add .Dispose() to it.



                                File.Create("filename").Dispose();



                                This way it creates and closes the file for the next process to use it.






                                share|improve this answer













                                I know this is an old question, but I just want to throw this out there that you can still use File.Create("filename")", just add .Dispose() to it.



                                File.Create("filename").Dispose();



                                This way it creates and closes the file for the next process to use it.







                                share|improve this answer












                                share|improve this answer



                                share|improve this answer










                                answered Jan 5 '18 at 16:13









                                IamBatmanIamBatman

                                6861018




                                6861018













                                • File.Create(FilePath).Close(); from the answer above has this.Dispose(true); GC.SuppressFinalize((object) this); in its implementation.

                                  – Ghukas
                                  2 days ago



















                                • File.Create(FilePath).Close(); from the answer above has this.Dispose(true); GC.SuppressFinalize((object) this); in its implementation.

                                  – Ghukas
                                  2 days ago

















                                File.Create(FilePath).Close(); from the answer above has this.Dispose(true); GC.SuppressFinalize((object) this); in its implementation.

                                – Ghukas
                                2 days ago





                                File.Create(FilePath).Close(); from the answer above has this.Dispose(true); GC.SuppressFinalize((object) this); in its implementation.

                                – Ghukas
                                2 days ago











                                0














                                Finally, I think I know the reason for this exception. You might be running this code snippet in multiple threads.






                                share|improve this answer




























                                  0














                                  Finally, I think I know the reason for this exception. You might be running this code snippet in multiple threads.






                                  share|improve this answer


























                                    0












                                    0








                                    0







                                    Finally, I think I know the reason for this exception. You might be running this code snippet in multiple threads.






                                    share|improve this answer













                                    Finally, I think I know the reason for this exception. You might be running this code snippet in multiple threads.







                                    share|improve this answer












                                    share|improve this answer



                                    share|improve this answer










                                    answered Aug 2 '18 at 18:59









                                    Kusala SubasingheKusala Subasinghe

                                    1




                                    1























                                        -1














                                        Try this: It works in any case, if the file doesn't exists, it will create it and then write to it. And if already exists, no problem it will open and write to it :



                                        using (FileStream fs= new FileStream(@"File.txt",FileMode.Create,FileAccess.ReadWrite))
                                        {
                                        fs.close();
                                        }
                                        using (StreamWriter sw = new StreamWriter(@"File.txt"))
                                        {
                                        sw.WriteLine("bla bla bla");
                                        sw.Close();
                                        }





                                        share|improve this answer





















                                        • 1





                                          using will close file by call Dispose. In your sample file was closed twice

                                          – Valentine Zakharenko
                                          Sep 20 '16 at 4:24
















                                        -1














                                        Try this: It works in any case, if the file doesn't exists, it will create it and then write to it. And if already exists, no problem it will open and write to it :



                                        using (FileStream fs= new FileStream(@"File.txt",FileMode.Create,FileAccess.ReadWrite))
                                        {
                                        fs.close();
                                        }
                                        using (StreamWriter sw = new StreamWriter(@"File.txt"))
                                        {
                                        sw.WriteLine("bla bla bla");
                                        sw.Close();
                                        }





                                        share|improve this answer





















                                        • 1





                                          using will close file by call Dispose. In your sample file was closed twice

                                          – Valentine Zakharenko
                                          Sep 20 '16 at 4:24














                                        -1












                                        -1








                                        -1







                                        Try this: It works in any case, if the file doesn't exists, it will create it and then write to it. And if already exists, no problem it will open and write to it :



                                        using (FileStream fs= new FileStream(@"File.txt",FileMode.Create,FileAccess.ReadWrite))
                                        {
                                        fs.close();
                                        }
                                        using (StreamWriter sw = new StreamWriter(@"File.txt"))
                                        {
                                        sw.WriteLine("bla bla bla");
                                        sw.Close();
                                        }





                                        share|improve this answer















                                        Try this: It works in any case, if the file doesn't exists, it will create it and then write to it. And if already exists, no problem it will open and write to it :



                                        using (FileStream fs= new FileStream(@"File.txt",FileMode.Create,FileAccess.ReadWrite))
                                        {
                                        fs.close();
                                        }
                                        using (StreamWriter sw = new StreamWriter(@"File.txt"))
                                        {
                                        sw.WriteLine("bla bla bla");
                                        sw.Close();
                                        }






                                        share|improve this answer














                                        share|improve this answer



                                        share|improve this answer








                                        edited Feb 12 '13 at 10:39

























                                        answered Feb 12 '13 at 10:28









                                        PureSilencePureSilence

                                        20723




                                        20723








                                        • 1





                                          using will close file by call Dispose. In your sample file was closed twice

                                          – Valentine Zakharenko
                                          Sep 20 '16 at 4:24














                                        • 1





                                          using will close file by call Dispose. In your sample file was closed twice

                                          – Valentine Zakharenko
                                          Sep 20 '16 at 4:24








                                        1




                                        1





                                        using will close file by call Dispose. In your sample file was closed twice

                                        – Valentine Zakharenko
                                        Sep 20 '16 at 4:24





                                        using will close file by call Dispose. In your sample file was closed twice

                                        – Valentine Zakharenko
                                        Sep 20 '16 at 4:24


















                                        draft saved

                                        draft discarded




















































                                        Thanks for contributing an answer to Stack Overflow!


                                        • Please be sure to answer the question. Provide details and share your research!

                                        But avoid



                                        • Asking for help, clarification, or responding to other answers.

                                        • Making statements based on opinion; back them up with references or personal experience.


                                        To learn more, see our tips on writing great answers.




                                        draft saved


                                        draft discarded














                                        StackExchange.ready(
                                        function () {
                                        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f2781357%2ffile-being-used-by-another-process-after-using-file-create%23new-answer', 'question_page');
                                        }
                                        );

                                        Post as a guest















                                        Required, but never shown





















































                                        Required, but never shown














                                        Required, but never shown












                                        Required, but never shown







                                        Required, but never shown

































                                        Required, but never shown














                                        Required, but never shown












                                        Required, but never shown







                                        Required, but never shown







                                        Popular posts from this blog

                                        Berounka

                                        Fiat S.p.A.

                                        Type 'String' is not a subtype of type 'int' of 'index'