Write lines in file when the file exists c# Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!What is the difference between String and string in C#?Cast int to enum in C#How do I check whether a file exists without exceptions?How do I enumerate an enum in C#?How do I copy a file in Python?How to create Excel (.XLS and .XLSX) file in C# without installing Ms Office?What are the correct version numbers for C#?How do I include a JavaScript file in another JavaScript file?Writing files in Node.jsHow to read a file line-by-line into a list?

Statistical analysis applied to methods coming out of Machine Learning

Did John Wesley plagiarize Matthew Henry...?

How many time has Arya actually used Needle?

How to ask rejected full-time candidates to apply to teach individual courses?

Baking rewards as operations

Can two people see the same photon?

Derived column in a data extension

Is it OK to use the testing sample to compare algorithms?

Is there a verb for listening stealthily?

Why can't fire hurt Daenerys but it did to Jon Snow in season 1?

Centre cell vertically in tabularx

Found this skink in my tomato plant bucket. Is he trapped? Or could he leave if he wanted?

latest version of QGIS fails to edit attribute table of GeoJSON file

French equivalents of おしゃれは足元から (Every good outfit starts with the shoes)

Short story about astronauts fertilizing soil with their own bodies

Besides transaction validation, are there any other uses of the Script language in Bitcoin

Why is there so little support for joining EFTA in the British parliament?

How to make triangles with rounded sides and corners? (squircle with 3 sides)

Why do C and C++ allow the expression (int) + 4*5;

What did Turing mean when saying that "machines cannot give rise to surprises" is due to a fallacy?

.bashrc alias for a command with fixed second parameter

Is this Half-dragon Quaggoth boss monster balanced?

2018 MacBook Pro won't let me install macOS High Sierra 10.13 from USB installer

What is "Lambda" in Heston's original paper on stochastic volatility models?



Write lines in file when the file exists c#



Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern)
Data science time! April 2019 and salary with experience
The Ask Question Wizard is Live!What is the difference between String and string in C#?Cast int to enum in C#How do I check whether a file exists without exceptions?How do I enumerate an enum in C#?How do I copy a file in Python?How to create Excel (.XLS and .XLSX) file in C# without installing Ms Office?What are the correct version numbers for C#?How do I include a JavaScript file in another JavaScript file?Writing files in Node.jsHow to read a file line-by-line into a list?



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








-4















i try to write line in file when this exists:



My code is next:



string strRuta = "C:File.txt"

if (!Directory.Exists(strRuta))
Directory.CreateDirectory(strRuta);


string psContenido = "Hola";

if (!(File.Exists(strRuta + strNombreArchivo)))

swArchivo = File.CreateText(strRuta + strNombreArchivo);



if (!psContenido.ToLower().Contains("error"))

swArchivo.WriteLine(psContenido);

swArchivo.Flush();
swArchivo.Close();
swArchivo.Dispose();
File.SetCreationTime(strRuta + strNombreArchivo, DateTime.Now);



but when run this program i have a error in WriteLine, i don´t undertand which is the reason, could you help me?



I would like to know how to write in the file(in the next line the word)










share|improve this question



















  • 1





    I could duplicate-close this for the common NullReferenceException you are obviously getting, but that's not the most important point here. Everything before if (!psContenido... could be just swArchivo = File.AppendText(strRuta + strNombreArchivo) (or even better, using Path.Combine), why you ask? Because File.AppendText "Creates a StreamWriter that appends UTF-8 encoded text to an existing file, or to a new file if the specified file does not exist." according to the docs

    – Camilo Terevinto
    Mar 9 at 0:48











  • Just pointing out that writing to the root c: directory in modern versions of windows is at best discouraged, and at worst prohibited. Write to C:tempFile.txt instead.

    – stuartd
    Mar 9 at 0:57






  • 1





    I have a error is not a useful problem description unless you also tell us what error you have. There's an error message that comes with that error, and it's right on the screen in front of you. Unfortunately, we cannot see your screen, so you need to give us that information in your question. It makes it much easier to help you fix an error when we know what the error is, and you have that information right in front of you.

    – Ken White
    Mar 9 at 1:07











  • You can replace all that CreateText, WriteLine, Flush, Close, and Dispose code with: File.AppendAllText(strRuta + strNombreArchivo, psContenido + "n"); The AppendAllText method will create the file if it doesn't exist, and then append the text to the end of the file, and then close it. Look into the File class - it has a bunch of very helpful methods for dealing with files that handle all the stream reader/writer stuff for you.

    – Rufus L
    Mar 9 at 1:19


















-4















i try to write line in file when this exists:



My code is next:



string strRuta = "C:File.txt"

if (!Directory.Exists(strRuta))
Directory.CreateDirectory(strRuta);


string psContenido = "Hola";

if (!(File.Exists(strRuta + strNombreArchivo)))

swArchivo = File.CreateText(strRuta + strNombreArchivo);



if (!psContenido.ToLower().Contains("error"))

swArchivo.WriteLine(psContenido);

swArchivo.Flush();
swArchivo.Close();
swArchivo.Dispose();
File.SetCreationTime(strRuta + strNombreArchivo, DateTime.Now);



but when run this program i have a error in WriteLine, i don´t undertand which is the reason, could you help me?



I would like to know how to write in the file(in the next line the word)










share|improve this question



















  • 1





    I could duplicate-close this for the common NullReferenceException you are obviously getting, but that's not the most important point here. Everything before if (!psContenido... could be just swArchivo = File.AppendText(strRuta + strNombreArchivo) (or even better, using Path.Combine), why you ask? Because File.AppendText "Creates a StreamWriter that appends UTF-8 encoded text to an existing file, or to a new file if the specified file does not exist." according to the docs

    – Camilo Terevinto
    Mar 9 at 0:48











  • Just pointing out that writing to the root c: directory in modern versions of windows is at best discouraged, and at worst prohibited. Write to C:tempFile.txt instead.

    – stuartd
    Mar 9 at 0:57






  • 1





    I have a error is not a useful problem description unless you also tell us what error you have. There's an error message that comes with that error, and it's right on the screen in front of you. Unfortunately, we cannot see your screen, so you need to give us that information in your question. It makes it much easier to help you fix an error when we know what the error is, and you have that information right in front of you.

    – Ken White
    Mar 9 at 1:07











  • You can replace all that CreateText, WriteLine, Flush, Close, and Dispose code with: File.AppendAllText(strRuta + strNombreArchivo, psContenido + "n"); The AppendAllText method will create the file if it doesn't exist, and then append the text to the end of the file, and then close it. Look into the File class - it has a bunch of very helpful methods for dealing with files that handle all the stream reader/writer stuff for you.

    – Rufus L
    Mar 9 at 1:19














-4












-4








-4








i try to write line in file when this exists:



My code is next:



string strRuta = "C:File.txt"

if (!Directory.Exists(strRuta))
Directory.CreateDirectory(strRuta);


string psContenido = "Hola";

if (!(File.Exists(strRuta + strNombreArchivo)))

swArchivo = File.CreateText(strRuta + strNombreArchivo);



if (!psContenido.ToLower().Contains("error"))

swArchivo.WriteLine(psContenido);

swArchivo.Flush();
swArchivo.Close();
swArchivo.Dispose();
File.SetCreationTime(strRuta + strNombreArchivo, DateTime.Now);



but when run this program i have a error in WriteLine, i don´t undertand which is the reason, could you help me?



I would like to know how to write in the file(in the next line the word)










share|improve this question
















i try to write line in file when this exists:



My code is next:



string strRuta = "C:File.txt"

if (!Directory.Exists(strRuta))
Directory.CreateDirectory(strRuta);


string psContenido = "Hola";

if (!(File.Exists(strRuta + strNombreArchivo)))

swArchivo = File.CreateText(strRuta + strNombreArchivo);



if (!psContenido.ToLower().Contains("error"))

swArchivo.WriteLine(psContenido);

swArchivo.Flush();
swArchivo.Close();
swArchivo.Dispose();
File.SetCreationTime(strRuta + strNombreArchivo, DateTime.Now);



but when run this program i have a error in WriteLine, i don´t undertand which is the reason, could you help me?



I would like to know how to write in the file(in the next line the word)







c# file






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 9 at 0:55









stuartd

51.8k11101129




51.8k11101129










asked Mar 9 at 0:39









AlexZAlexZ

685




685







  • 1





    I could duplicate-close this for the common NullReferenceException you are obviously getting, but that's not the most important point here. Everything before if (!psContenido... could be just swArchivo = File.AppendText(strRuta + strNombreArchivo) (or even better, using Path.Combine), why you ask? Because File.AppendText "Creates a StreamWriter that appends UTF-8 encoded text to an existing file, or to a new file if the specified file does not exist." according to the docs

    – Camilo Terevinto
    Mar 9 at 0:48











  • Just pointing out that writing to the root c: directory in modern versions of windows is at best discouraged, and at worst prohibited. Write to C:tempFile.txt instead.

    – stuartd
    Mar 9 at 0:57






  • 1





    I have a error is not a useful problem description unless you also tell us what error you have. There's an error message that comes with that error, and it's right on the screen in front of you. Unfortunately, we cannot see your screen, so you need to give us that information in your question. It makes it much easier to help you fix an error when we know what the error is, and you have that information right in front of you.

    – Ken White
    Mar 9 at 1:07











  • You can replace all that CreateText, WriteLine, Flush, Close, and Dispose code with: File.AppendAllText(strRuta + strNombreArchivo, psContenido + "n"); The AppendAllText method will create the file if it doesn't exist, and then append the text to the end of the file, and then close it. Look into the File class - it has a bunch of very helpful methods for dealing with files that handle all the stream reader/writer stuff for you.

    – Rufus L
    Mar 9 at 1:19













  • 1





    I could duplicate-close this for the common NullReferenceException you are obviously getting, but that's not the most important point here. Everything before if (!psContenido... could be just swArchivo = File.AppendText(strRuta + strNombreArchivo) (or even better, using Path.Combine), why you ask? Because File.AppendText "Creates a StreamWriter that appends UTF-8 encoded text to an existing file, or to a new file if the specified file does not exist." according to the docs

    – Camilo Terevinto
    Mar 9 at 0:48











  • Just pointing out that writing to the root c: directory in modern versions of windows is at best discouraged, and at worst prohibited. Write to C:tempFile.txt instead.

    – stuartd
    Mar 9 at 0:57






  • 1





    I have a error is not a useful problem description unless you also tell us what error you have. There's an error message that comes with that error, and it's right on the screen in front of you. Unfortunately, we cannot see your screen, so you need to give us that information in your question. It makes it much easier to help you fix an error when we know what the error is, and you have that information right in front of you.

    – Ken White
    Mar 9 at 1:07











  • You can replace all that CreateText, WriteLine, Flush, Close, and Dispose code with: File.AppendAllText(strRuta + strNombreArchivo, psContenido + "n"); The AppendAllText method will create the file if it doesn't exist, and then append the text to the end of the file, and then close it. Look into the File class - it has a bunch of very helpful methods for dealing with files that handle all the stream reader/writer stuff for you.

    – Rufus L
    Mar 9 at 1:19








1




1





I could duplicate-close this for the common NullReferenceException you are obviously getting, but that's not the most important point here. Everything before if (!psContenido... could be just swArchivo = File.AppendText(strRuta + strNombreArchivo) (or even better, using Path.Combine), why you ask? Because File.AppendText "Creates a StreamWriter that appends UTF-8 encoded text to an existing file, or to a new file if the specified file does not exist." according to the docs

– Camilo Terevinto
Mar 9 at 0:48





I could duplicate-close this for the common NullReferenceException you are obviously getting, but that's not the most important point here. Everything before if (!psContenido... could be just swArchivo = File.AppendText(strRuta + strNombreArchivo) (or even better, using Path.Combine), why you ask? Because File.AppendText "Creates a StreamWriter that appends UTF-8 encoded text to an existing file, or to a new file if the specified file does not exist." according to the docs

– Camilo Terevinto
Mar 9 at 0:48













Just pointing out that writing to the root c: directory in modern versions of windows is at best discouraged, and at worst prohibited. Write to C:tempFile.txt instead.

– stuartd
Mar 9 at 0:57





Just pointing out that writing to the root c: directory in modern versions of windows is at best discouraged, and at worst prohibited. Write to C:tempFile.txt instead.

– stuartd
Mar 9 at 0:57




1




1





I have a error is not a useful problem description unless you also tell us what error you have. There's an error message that comes with that error, and it's right on the screen in front of you. Unfortunately, we cannot see your screen, so you need to give us that information in your question. It makes it much easier to help you fix an error when we know what the error is, and you have that information right in front of you.

– Ken White
Mar 9 at 1:07





I have a error is not a useful problem description unless you also tell us what error you have. There's an error message that comes with that error, and it's right on the screen in front of you. Unfortunately, we cannot see your screen, so you need to give us that information in your question. It makes it much easier to help you fix an error when we know what the error is, and you have that information right in front of you.

– Ken White
Mar 9 at 1:07













You can replace all that CreateText, WriteLine, Flush, Close, and Dispose code with: File.AppendAllText(strRuta + strNombreArchivo, psContenido + "n"); The AppendAllText method will create the file if it doesn't exist, and then append the text to the end of the file, and then close it. Look into the File class - it has a bunch of very helpful methods for dealing with files that handle all the stream reader/writer stuff for you.

– Rufus L
Mar 9 at 1:19






You can replace all that CreateText, WriteLine, Flush, Close, and Dispose code with: File.AppendAllText(strRuta + strNombreArchivo, psContenido + "n"); The AppendAllText method will create the file if it doesn't exist, and then append the text to the end of the file, and then close it. Look into the File class - it has a bunch of very helpful methods for dealing with files that handle all the stream reader/writer stuff for you.

– Rufus L
Mar 9 at 1:19













1 Answer
1






active

oldest

votes


















0














There are a couple of problems, I think. First, you're specifying what looks like a file name and creating a directory with that name (not sure if this is intentional or not). Second, you can use the static helper method AppendAllText of the File class to both create the file if it doesn't exist, and to write the contents to the end of the file. It handles all the streamwriter stuff for you, so you don't have to worry about calling close and dispose.



private static void Main(string[] args)

string directory = @"C:privatetemp";
string fileName = "MyFile.txt";
string filePath = Path.Combine(directory, fileName);
string fileContents = "This will be written to the end of the filern";

// This will create the directory if it doesn't exist
Directory.CreateDirectory(directory);

// This will create the file if it doesn't exist, and then write the text at the end.
File.AppendAllText(filePath, fileContents);

File.SetCreationTime(filePath, DateTime.Now);






share|improve this answer























    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%2f55072858%2fwrite-lines-in-file-when-the-file-exists-c-sharp%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    There are a couple of problems, I think. First, you're specifying what looks like a file name and creating a directory with that name (not sure if this is intentional or not). Second, you can use the static helper method AppendAllText of the File class to both create the file if it doesn't exist, and to write the contents to the end of the file. It handles all the streamwriter stuff for you, so you don't have to worry about calling close and dispose.



    private static void Main(string[] args)

    string directory = @"C:privatetemp";
    string fileName = "MyFile.txt";
    string filePath = Path.Combine(directory, fileName);
    string fileContents = "This will be written to the end of the filern";

    // This will create the directory if it doesn't exist
    Directory.CreateDirectory(directory);

    // This will create the file if it doesn't exist, and then write the text at the end.
    File.AppendAllText(filePath, fileContents);

    File.SetCreationTime(filePath, DateTime.Now);






    share|improve this answer



























      0














      There are a couple of problems, I think. First, you're specifying what looks like a file name and creating a directory with that name (not sure if this is intentional or not). Second, you can use the static helper method AppendAllText of the File class to both create the file if it doesn't exist, and to write the contents to the end of the file. It handles all the streamwriter stuff for you, so you don't have to worry about calling close and dispose.



      private static void Main(string[] args)

      string directory = @"C:privatetemp";
      string fileName = "MyFile.txt";
      string filePath = Path.Combine(directory, fileName);
      string fileContents = "This will be written to the end of the filern";

      // This will create the directory if it doesn't exist
      Directory.CreateDirectory(directory);

      // This will create the file if it doesn't exist, and then write the text at the end.
      File.AppendAllText(filePath, fileContents);

      File.SetCreationTime(filePath, DateTime.Now);






      share|improve this answer

























        0












        0








        0







        There are a couple of problems, I think. First, you're specifying what looks like a file name and creating a directory with that name (not sure if this is intentional or not). Second, you can use the static helper method AppendAllText of the File class to both create the file if it doesn't exist, and to write the contents to the end of the file. It handles all the streamwriter stuff for you, so you don't have to worry about calling close and dispose.



        private static void Main(string[] args)

        string directory = @"C:privatetemp";
        string fileName = "MyFile.txt";
        string filePath = Path.Combine(directory, fileName);
        string fileContents = "This will be written to the end of the filern";

        // This will create the directory if it doesn't exist
        Directory.CreateDirectory(directory);

        // This will create the file if it doesn't exist, and then write the text at the end.
        File.AppendAllText(filePath, fileContents);

        File.SetCreationTime(filePath, DateTime.Now);






        share|improve this answer













        There are a couple of problems, I think. First, you're specifying what looks like a file name and creating a directory with that name (not sure if this is intentional or not). Second, you can use the static helper method AppendAllText of the File class to both create the file if it doesn't exist, and to write the contents to the end of the file. It handles all the streamwriter stuff for you, so you don't have to worry about calling close and dispose.



        private static void Main(string[] args)

        string directory = @"C:privatetemp";
        string fileName = "MyFile.txt";
        string filePath = Path.Combine(directory, fileName);
        string fileContents = "This will be written to the end of the filern";

        // This will create the directory if it doesn't exist
        Directory.CreateDirectory(directory);

        // This will create the file if it doesn't exist, and then write the text at the end.
        File.AppendAllText(filePath, fileContents);

        File.SetCreationTime(filePath, DateTime.Now);







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 9 at 2:27









        Rufus LRufus L

        19.5k31732




        19.5k31732





























            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%2f55072858%2fwrite-lines-in-file-when-the-file-exists-c-sharp%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

            1928 у кіно

            Захаров Федір Захарович

            Ель Греко