Replacing a part of a string from a text file












0















I want to replace the second part of the string line of my .txt file. My .txt is:



admin|admin
ruiliberal|123456789


And I want to replace it like this for example:



admin|12345
ruiliberal|123456789


My code is:



string dirConta = Environment.CurrentDirectory + "/Bd/contas.txt";

private void buttonGravaPass_Click(object sender, EventArgs e)
{
string lines = File.ReadLines(dirConta).ToArray();

for (int i = 0; i < File.ReadAllLines(dirConta).Count(); i++)
{

string parts = lines[i].Split(new char { '|' });
if (parts[0] == Users.user)
{
lines[i] = lines[i].Remove(lines[i].Length - 5);
lines[i] = lines[i] + "12345";
}
File.WriteAllText(dirConta, lines[i]);
}
}


This doesn´t work, it deletes the last line.










share|improve this question

























  • Why call ReadLines(), then subsequently call ReadAllLines()? There is so much wrong with this

    – maccettura
    Nov 20 '18 at 20:53













  • Because it doens´t work if I did not @maccettura

    – Rui Liberal
    Nov 20 '18 at 20:54











  • Loop through lines in a file using File.ReadLines() in a For Each loop see here.

    – JNevill
    Nov 20 '18 at 20:58











  • @RuiLiberal what you are doing does not make sense though, and you cannot claim it works now because the very essence of your question is that it does not work. You need to read the documentation more. You should be iterating the return of File.ReadLines(), splitting each line inside the loop, build a new string and add that to an "output" list. Then use File.WriteLines() to write back to the file

    – maccettura
    Nov 20 '18 at 21:00






  • 1





    So what you're telling is that you store passwords in plain text, against all reason?

    – Joel Coehoorn
    Nov 20 '18 at 21:09
















0















I want to replace the second part of the string line of my .txt file. My .txt is:



admin|admin
ruiliberal|123456789


And I want to replace it like this for example:



admin|12345
ruiliberal|123456789


My code is:



string dirConta = Environment.CurrentDirectory + "/Bd/contas.txt";

private void buttonGravaPass_Click(object sender, EventArgs e)
{
string lines = File.ReadLines(dirConta).ToArray();

for (int i = 0; i < File.ReadAllLines(dirConta).Count(); i++)
{

string parts = lines[i].Split(new char { '|' });
if (parts[0] == Users.user)
{
lines[i] = lines[i].Remove(lines[i].Length - 5);
lines[i] = lines[i] + "12345";
}
File.WriteAllText(dirConta, lines[i]);
}
}


This doesn´t work, it deletes the last line.










share|improve this question

























  • Why call ReadLines(), then subsequently call ReadAllLines()? There is so much wrong with this

    – maccettura
    Nov 20 '18 at 20:53













  • Because it doens´t work if I did not @maccettura

    – Rui Liberal
    Nov 20 '18 at 20:54











  • Loop through lines in a file using File.ReadLines() in a For Each loop see here.

    – JNevill
    Nov 20 '18 at 20:58











  • @RuiLiberal what you are doing does not make sense though, and you cannot claim it works now because the very essence of your question is that it does not work. You need to read the documentation more. You should be iterating the return of File.ReadLines(), splitting each line inside the loop, build a new string and add that to an "output" list. Then use File.WriteLines() to write back to the file

    – maccettura
    Nov 20 '18 at 21:00






  • 1





    So what you're telling is that you store passwords in plain text, against all reason?

    – Joel Coehoorn
    Nov 20 '18 at 21:09














0












0








0








I want to replace the second part of the string line of my .txt file. My .txt is:



admin|admin
ruiliberal|123456789


And I want to replace it like this for example:



admin|12345
ruiliberal|123456789


My code is:



string dirConta = Environment.CurrentDirectory + "/Bd/contas.txt";

private void buttonGravaPass_Click(object sender, EventArgs e)
{
string lines = File.ReadLines(dirConta).ToArray();

for (int i = 0; i < File.ReadAllLines(dirConta).Count(); i++)
{

string parts = lines[i].Split(new char { '|' });
if (parts[0] == Users.user)
{
lines[i] = lines[i].Remove(lines[i].Length - 5);
lines[i] = lines[i] + "12345";
}
File.WriteAllText(dirConta, lines[i]);
}
}


This doesn´t work, it deletes the last line.










share|improve this question
















I want to replace the second part of the string line of my .txt file. My .txt is:



admin|admin
ruiliberal|123456789


And I want to replace it like this for example:



admin|12345
ruiliberal|123456789


My code is:



string dirConta = Environment.CurrentDirectory + "/Bd/contas.txt";

private void buttonGravaPass_Click(object sender, EventArgs e)
{
string lines = File.ReadLines(dirConta).ToArray();

for (int i = 0; i < File.ReadAllLines(dirConta).Count(); i++)
{

string parts = lines[i].Split(new char { '|' });
if (parts[0] == Users.user)
{
lines[i] = lines[i].Remove(lines[i].Length - 5);
lines[i] = lines[i] + "12345";
}
File.WriteAllText(dirConta, lines[i]);
}
}


This doesn´t work, it deletes the last line.







c#






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 20 '18 at 21:09









Joel Coehoorn

310k96495730




310k96495730










asked Nov 20 '18 at 20:50









Rui LiberalRui Liberal

185




185













  • Why call ReadLines(), then subsequently call ReadAllLines()? There is so much wrong with this

    – maccettura
    Nov 20 '18 at 20:53













  • Because it doens´t work if I did not @maccettura

    – Rui Liberal
    Nov 20 '18 at 20:54











  • Loop through lines in a file using File.ReadLines() in a For Each loop see here.

    – JNevill
    Nov 20 '18 at 20:58











  • @RuiLiberal what you are doing does not make sense though, and you cannot claim it works now because the very essence of your question is that it does not work. You need to read the documentation more. You should be iterating the return of File.ReadLines(), splitting each line inside the loop, build a new string and add that to an "output" list. Then use File.WriteLines() to write back to the file

    – maccettura
    Nov 20 '18 at 21:00






  • 1





    So what you're telling is that you store passwords in plain text, against all reason?

    – Joel Coehoorn
    Nov 20 '18 at 21:09



















  • Why call ReadLines(), then subsequently call ReadAllLines()? There is so much wrong with this

    – maccettura
    Nov 20 '18 at 20:53













  • Because it doens´t work if I did not @maccettura

    – Rui Liberal
    Nov 20 '18 at 20:54











  • Loop through lines in a file using File.ReadLines() in a For Each loop see here.

    – JNevill
    Nov 20 '18 at 20:58











  • @RuiLiberal what you are doing does not make sense though, and you cannot claim it works now because the very essence of your question is that it does not work. You need to read the documentation more. You should be iterating the return of File.ReadLines(), splitting each line inside the loop, build a new string and add that to an "output" list. Then use File.WriteLines() to write back to the file

    – maccettura
    Nov 20 '18 at 21:00






  • 1





    So what you're telling is that you store passwords in plain text, against all reason?

    – Joel Coehoorn
    Nov 20 '18 at 21:09

















Why call ReadLines(), then subsequently call ReadAllLines()? There is so much wrong with this

– maccettura
Nov 20 '18 at 20:53







Why call ReadLines(), then subsequently call ReadAllLines()? There is so much wrong with this

– maccettura
Nov 20 '18 at 20:53















Because it doens´t work if I did not @maccettura

– Rui Liberal
Nov 20 '18 at 20:54





Because it doens´t work if I did not @maccettura

– Rui Liberal
Nov 20 '18 at 20:54













Loop through lines in a file using File.ReadLines() in a For Each loop see here.

– JNevill
Nov 20 '18 at 20:58





Loop through lines in a file using File.ReadLines() in a For Each loop see here.

– JNevill
Nov 20 '18 at 20:58













@RuiLiberal what you are doing does not make sense though, and you cannot claim it works now because the very essence of your question is that it does not work. You need to read the documentation more. You should be iterating the return of File.ReadLines(), splitting each line inside the loop, build a new string and add that to an "output" list. Then use File.WriteLines() to write back to the file

– maccettura
Nov 20 '18 at 21:00





@RuiLiberal what you are doing does not make sense though, and you cannot claim it works now because the very essence of your question is that it does not work. You need to read the documentation more. You should be iterating the return of File.ReadLines(), splitting each line inside the loop, build a new string and add that to an "output" list. Then use File.WriteLines() to write back to the file

– maccettura
Nov 20 '18 at 21:00




1




1





So what you're telling is that you store passwords in plain text, against all reason?

– Joel Coehoorn
Nov 20 '18 at 21:09





So what you're telling is that you store passwords in plain text, against all reason?

– Joel Coehoorn
Nov 20 '18 at 21:09












5 Answers
5






active

oldest

votes


















2














There are a few issues with your code.



First problem is: never store passwords in plain text. This is a horrible idea. If this is a production system, stop what you are doing and start from the ground up because this is bad. If this is just an exercise in learning and is not for any real future use then continue on...



Second, you are calling File.ReadLines() and File.ReadAllLines(), you dont need both. Just use File.ReadLines() as it returns an IEnumerable and lets you work on the results as they come in instead of waiting for all to be returned (which is what File.ReadAllLines() does).



Next, you should make a method that actually does the modification for you so you can reuse it if needed:



private static IEnumerable<string> ModifyLines(IEnumerable<string> inputLines)
{
foreach(var line in inputLines)
{
var split = line.Split('|');
yield return $"{split[0]}|12345";
}
}


This will iterate the input IEnumerable, and yield return a new string. There really isn't any reason to modify the split array, just take the string you need (the username) and use string interpolation to format it with your static password ("12345").



Then when all is said and done you need to use File.WriteAllLines() method to write the results to file, not File.WriteAllText(). One of the reasons your code does not work is because you write all text inside the loop. If you read the docs to see what the method actually does you will see why it would not work the way you are using it.



So all together it would be:



private void buttonGravaPass_Click(object sender, EventArgs e)
{
var lines = ModifyLines(File.ReadLines(dirConta));
File.WriteAllLines(dirConta, lines.ToArray());
}


Fiddle here






share|improve this answer

































    1














    Here's my spin on it...



    using System;
    using System.Collections.Generic;
    using System.IO;

    namespace Q_53401300
    {
    class Program
    {

    static string dirConta = "C:\temp2\ListOfPWD.txt";

    static void Main(string args)
    {
    buttonGravaPass_Click(null, null);

    }

    private static void buttonGravaPass_Click(object sender, EventArgs e)
    {
    List<string> newLinesToWrite = new List<string>();
    using (System.IO.StreamReader sr = new StreamReader(dirConta))
    {
    string currentLine = string.Empty;
    while ((currentLine = sr.ReadLine()) != null)
    {
    string parts = currentLine.Split(new char { '|' });
    //if (parts[0] == Users.user)
    //{
    parts[0] = parts[0].Remove(parts[0].Length - 5);
    parts[1] = parts[1] + "12345";
    newLinesToWrite.Add($"{parts[0]}|{parts[1]}");
    //}
    }
    }
    System.IO.File.WriteAllLines(dirConta, newLinesToWrite);
    }
    }
    }





    share|improve this answer
























    • Just so you are aware, File.ReadLines() uses a StreamReader under the hood.

      – maccettura
      Nov 20 '18 at 21:23











    • @maccettura - Correct, but I deal with larger files and StreamReader has been more reliable over time.

      – blaze_125
      Nov 21 '18 at 2:18





















    1














    Just in case you want to use your code here is the tested working version just change the lines in your code related to the ones below:



    string lines = File.ReadLines(dirConta).ToArray();

    for (int i = 0; i < lines.Length; i++)
    {

    string parts = lines[i].Split(new char { '|' });
    if (parts[0] == Users.user)
    {
    lines[i] = lines[i].Remove(lines[i].Length - 5);
    lines[i] = lines[i] + "12345";
    }

    }
    File.WriteAllText(dirConta, string.Join("n",lines));


    I hope this help as the other answers pointed what miss with the code.






    share|improve this answer

































      0














      So in my opinion there are a few things wrong with this code.



      1.) Your for-loop:



      for(int i = 0; i < lines.Count(); i++)
      { [...] }


      you do not have to call ReadAllLines() again.
      Or do:



      foreach(string line in lines){[...]}


      2.) Splitting into the parts:
      Since you only have one splitting char you can call that like that:



      string parts = lines[i].Split('|');


      3.) Assigning the new string value:
      Why not just do that:



      lines[i] = $"{parts[0]}|12345";


      4.) I would not suggest to write to the file in every loop. Just put File.WriteAllText(dirConta, lines[i]); outside your for-loop



      5.) If you want to store data, I would strongly suggest to look into object-serialization. It makes alot of stuff easier.
      See: Json Serialization in C#






      share|improve this answer































        0














        There's a few problems with your approach. First, you should try to avoid + when concatenating strings. Use $"" or string.Format instead. Second, when event-programming, it's best to write another method that the event method calls so that you can avoid blocking the UI thread with unnecessary work (like writing to a file for example). Looking at the documentation for System.IO, it's possible to iterate over the lines of text using File.ReadLines so I did that instead of reading the file twice to get the number of lines. Also, instead of using Remove and +, just use Replace; it's much easier. Finally, you need to make sure you write all the text you have. Right now, you're only writing the first line.



        string dirConta = $"{Environment.CurrentDirectory}/Bd/contas.txt";

        private async Task ModifyFileAsync()
        {
        var output = new List<string>();
        using (var reader = new StreamReader(dirConta))
        {
        while ((var line = await reader.ReadLineAsync().ConfigureAwait(false)) != null)
        {
        var parts = line.Split('|');
        if (parts[0] == Users.user)
        {
        var newLine = line.Replace(parts[1], "12345");
        lines.Add(newLine);
        }
        else
        {
        lines.Add(line);
        }
        }
        }

        using (var writer = new StreamWriter(dirConta))
        {
        foreach (var line in lines)
        {
        await writer.WriteLineAsync(line).ConfigureAwait(false);
        }
        }
        }

        private async void buttonGravaPass_Click(object sender, EventArgs e)
        {
        await ModifyFileAsync().ConfigureAwait(false);
        }





        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%2f53401300%2freplacing-a-part-of-a-string-from-a-text-file%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          5 Answers
          5






          active

          oldest

          votes








          5 Answers
          5






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          2














          There are a few issues with your code.



          First problem is: never store passwords in plain text. This is a horrible idea. If this is a production system, stop what you are doing and start from the ground up because this is bad. If this is just an exercise in learning and is not for any real future use then continue on...



          Second, you are calling File.ReadLines() and File.ReadAllLines(), you dont need both. Just use File.ReadLines() as it returns an IEnumerable and lets you work on the results as they come in instead of waiting for all to be returned (which is what File.ReadAllLines() does).



          Next, you should make a method that actually does the modification for you so you can reuse it if needed:



          private static IEnumerable<string> ModifyLines(IEnumerable<string> inputLines)
          {
          foreach(var line in inputLines)
          {
          var split = line.Split('|');
          yield return $"{split[0]}|12345";
          }
          }


          This will iterate the input IEnumerable, and yield return a new string. There really isn't any reason to modify the split array, just take the string you need (the username) and use string interpolation to format it with your static password ("12345").



          Then when all is said and done you need to use File.WriteAllLines() method to write the results to file, not File.WriteAllText(). One of the reasons your code does not work is because you write all text inside the loop. If you read the docs to see what the method actually does you will see why it would not work the way you are using it.



          So all together it would be:



          private void buttonGravaPass_Click(object sender, EventArgs e)
          {
          var lines = ModifyLines(File.ReadLines(dirConta));
          File.WriteAllLines(dirConta, lines.ToArray());
          }


          Fiddle here






          share|improve this answer






























            2














            There are a few issues with your code.



            First problem is: never store passwords in plain text. This is a horrible idea. If this is a production system, stop what you are doing and start from the ground up because this is bad. If this is just an exercise in learning and is not for any real future use then continue on...



            Second, you are calling File.ReadLines() and File.ReadAllLines(), you dont need both. Just use File.ReadLines() as it returns an IEnumerable and lets you work on the results as they come in instead of waiting for all to be returned (which is what File.ReadAllLines() does).



            Next, you should make a method that actually does the modification for you so you can reuse it if needed:



            private static IEnumerable<string> ModifyLines(IEnumerable<string> inputLines)
            {
            foreach(var line in inputLines)
            {
            var split = line.Split('|');
            yield return $"{split[0]}|12345";
            }
            }


            This will iterate the input IEnumerable, and yield return a new string. There really isn't any reason to modify the split array, just take the string you need (the username) and use string interpolation to format it with your static password ("12345").



            Then when all is said and done you need to use File.WriteAllLines() method to write the results to file, not File.WriteAllText(). One of the reasons your code does not work is because you write all text inside the loop. If you read the docs to see what the method actually does you will see why it would not work the way you are using it.



            So all together it would be:



            private void buttonGravaPass_Click(object sender, EventArgs e)
            {
            var lines = ModifyLines(File.ReadLines(dirConta));
            File.WriteAllLines(dirConta, lines.ToArray());
            }


            Fiddle here






            share|improve this answer




























              2












              2








              2







              There are a few issues with your code.



              First problem is: never store passwords in plain text. This is a horrible idea. If this is a production system, stop what you are doing and start from the ground up because this is bad. If this is just an exercise in learning and is not for any real future use then continue on...



              Second, you are calling File.ReadLines() and File.ReadAllLines(), you dont need both. Just use File.ReadLines() as it returns an IEnumerable and lets you work on the results as they come in instead of waiting for all to be returned (which is what File.ReadAllLines() does).



              Next, you should make a method that actually does the modification for you so you can reuse it if needed:



              private static IEnumerable<string> ModifyLines(IEnumerable<string> inputLines)
              {
              foreach(var line in inputLines)
              {
              var split = line.Split('|');
              yield return $"{split[0]}|12345";
              }
              }


              This will iterate the input IEnumerable, and yield return a new string. There really isn't any reason to modify the split array, just take the string you need (the username) and use string interpolation to format it with your static password ("12345").



              Then when all is said and done you need to use File.WriteAllLines() method to write the results to file, not File.WriteAllText(). One of the reasons your code does not work is because you write all text inside the loop. If you read the docs to see what the method actually does you will see why it would not work the way you are using it.



              So all together it would be:



              private void buttonGravaPass_Click(object sender, EventArgs e)
              {
              var lines = ModifyLines(File.ReadLines(dirConta));
              File.WriteAllLines(dirConta, lines.ToArray());
              }


              Fiddle here






              share|improve this answer















              There are a few issues with your code.



              First problem is: never store passwords in plain text. This is a horrible idea. If this is a production system, stop what you are doing and start from the ground up because this is bad. If this is just an exercise in learning and is not for any real future use then continue on...



              Second, you are calling File.ReadLines() and File.ReadAllLines(), you dont need both. Just use File.ReadLines() as it returns an IEnumerable and lets you work on the results as they come in instead of waiting for all to be returned (which is what File.ReadAllLines() does).



              Next, you should make a method that actually does the modification for you so you can reuse it if needed:



              private static IEnumerable<string> ModifyLines(IEnumerable<string> inputLines)
              {
              foreach(var line in inputLines)
              {
              var split = line.Split('|');
              yield return $"{split[0]}|12345";
              }
              }


              This will iterate the input IEnumerable, and yield return a new string. There really isn't any reason to modify the split array, just take the string you need (the username) and use string interpolation to format it with your static password ("12345").



              Then when all is said and done you need to use File.WriteAllLines() method to write the results to file, not File.WriteAllText(). One of the reasons your code does not work is because you write all text inside the loop. If you read the docs to see what the method actually does you will see why it would not work the way you are using it.



              So all together it would be:



              private void buttonGravaPass_Click(object sender, EventArgs e)
              {
              var lines = ModifyLines(File.ReadLines(dirConta));
              File.WriteAllLines(dirConta, lines.ToArray());
              }


              Fiddle here







              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Nov 20 '18 at 21:27

























              answered Nov 20 '18 at 21:10









              maccetturamaccettura

              8,32931527




              8,32931527

























                  1














                  Here's my spin on it...



                  using System;
                  using System.Collections.Generic;
                  using System.IO;

                  namespace Q_53401300
                  {
                  class Program
                  {

                  static string dirConta = "C:\temp2\ListOfPWD.txt";

                  static void Main(string args)
                  {
                  buttonGravaPass_Click(null, null);

                  }

                  private static void buttonGravaPass_Click(object sender, EventArgs e)
                  {
                  List<string> newLinesToWrite = new List<string>();
                  using (System.IO.StreamReader sr = new StreamReader(dirConta))
                  {
                  string currentLine = string.Empty;
                  while ((currentLine = sr.ReadLine()) != null)
                  {
                  string parts = currentLine.Split(new char { '|' });
                  //if (parts[0] == Users.user)
                  //{
                  parts[0] = parts[0].Remove(parts[0].Length - 5);
                  parts[1] = parts[1] + "12345";
                  newLinesToWrite.Add($"{parts[0]}|{parts[1]}");
                  //}
                  }
                  }
                  System.IO.File.WriteAllLines(dirConta, newLinesToWrite);
                  }
                  }
                  }





                  share|improve this answer
























                  • Just so you are aware, File.ReadLines() uses a StreamReader under the hood.

                    – maccettura
                    Nov 20 '18 at 21:23











                  • @maccettura - Correct, but I deal with larger files and StreamReader has been more reliable over time.

                    – blaze_125
                    Nov 21 '18 at 2:18


















                  1














                  Here's my spin on it...



                  using System;
                  using System.Collections.Generic;
                  using System.IO;

                  namespace Q_53401300
                  {
                  class Program
                  {

                  static string dirConta = "C:\temp2\ListOfPWD.txt";

                  static void Main(string args)
                  {
                  buttonGravaPass_Click(null, null);

                  }

                  private static void buttonGravaPass_Click(object sender, EventArgs e)
                  {
                  List<string> newLinesToWrite = new List<string>();
                  using (System.IO.StreamReader sr = new StreamReader(dirConta))
                  {
                  string currentLine = string.Empty;
                  while ((currentLine = sr.ReadLine()) != null)
                  {
                  string parts = currentLine.Split(new char { '|' });
                  //if (parts[0] == Users.user)
                  //{
                  parts[0] = parts[0].Remove(parts[0].Length - 5);
                  parts[1] = parts[1] + "12345";
                  newLinesToWrite.Add($"{parts[0]}|{parts[1]}");
                  //}
                  }
                  }
                  System.IO.File.WriteAllLines(dirConta, newLinesToWrite);
                  }
                  }
                  }





                  share|improve this answer
























                  • Just so you are aware, File.ReadLines() uses a StreamReader under the hood.

                    – maccettura
                    Nov 20 '18 at 21:23











                  • @maccettura - Correct, but I deal with larger files and StreamReader has been more reliable over time.

                    – blaze_125
                    Nov 21 '18 at 2:18
















                  1












                  1








                  1







                  Here's my spin on it...



                  using System;
                  using System.Collections.Generic;
                  using System.IO;

                  namespace Q_53401300
                  {
                  class Program
                  {

                  static string dirConta = "C:\temp2\ListOfPWD.txt";

                  static void Main(string args)
                  {
                  buttonGravaPass_Click(null, null);

                  }

                  private static void buttonGravaPass_Click(object sender, EventArgs e)
                  {
                  List<string> newLinesToWrite = new List<string>();
                  using (System.IO.StreamReader sr = new StreamReader(dirConta))
                  {
                  string currentLine = string.Empty;
                  while ((currentLine = sr.ReadLine()) != null)
                  {
                  string parts = currentLine.Split(new char { '|' });
                  //if (parts[0] == Users.user)
                  //{
                  parts[0] = parts[0].Remove(parts[0].Length - 5);
                  parts[1] = parts[1] + "12345";
                  newLinesToWrite.Add($"{parts[0]}|{parts[1]}");
                  //}
                  }
                  }
                  System.IO.File.WriteAllLines(dirConta, newLinesToWrite);
                  }
                  }
                  }





                  share|improve this answer













                  Here's my spin on it...



                  using System;
                  using System.Collections.Generic;
                  using System.IO;

                  namespace Q_53401300
                  {
                  class Program
                  {

                  static string dirConta = "C:\temp2\ListOfPWD.txt";

                  static void Main(string args)
                  {
                  buttonGravaPass_Click(null, null);

                  }

                  private static void buttonGravaPass_Click(object sender, EventArgs e)
                  {
                  List<string> newLinesToWrite = new List<string>();
                  using (System.IO.StreamReader sr = new StreamReader(dirConta))
                  {
                  string currentLine = string.Empty;
                  while ((currentLine = sr.ReadLine()) != null)
                  {
                  string parts = currentLine.Split(new char { '|' });
                  //if (parts[0] == Users.user)
                  //{
                  parts[0] = parts[0].Remove(parts[0].Length - 5);
                  parts[1] = parts[1] + "12345";
                  newLinesToWrite.Add($"{parts[0]}|{parts[1]}");
                  //}
                  }
                  }
                  System.IO.File.WriteAllLines(dirConta, newLinesToWrite);
                  }
                  }
                  }






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 20 '18 at 21:04









                  blaze_125blaze_125

                  1,8871516




                  1,8871516













                  • Just so you are aware, File.ReadLines() uses a StreamReader under the hood.

                    – maccettura
                    Nov 20 '18 at 21:23











                  • @maccettura - Correct, but I deal with larger files and StreamReader has been more reliable over time.

                    – blaze_125
                    Nov 21 '18 at 2:18





















                  • Just so you are aware, File.ReadLines() uses a StreamReader under the hood.

                    – maccettura
                    Nov 20 '18 at 21:23











                  • @maccettura - Correct, but I deal with larger files and StreamReader has been more reliable over time.

                    – blaze_125
                    Nov 21 '18 at 2:18



















                  Just so you are aware, File.ReadLines() uses a StreamReader under the hood.

                  – maccettura
                  Nov 20 '18 at 21:23





                  Just so you are aware, File.ReadLines() uses a StreamReader under the hood.

                  – maccettura
                  Nov 20 '18 at 21:23













                  @maccettura - Correct, but I deal with larger files and StreamReader has been more reliable over time.

                  – blaze_125
                  Nov 21 '18 at 2:18







                  @maccettura - Correct, but I deal with larger files and StreamReader has been more reliable over time.

                  – blaze_125
                  Nov 21 '18 at 2:18













                  1














                  Just in case you want to use your code here is the tested working version just change the lines in your code related to the ones below:



                  string lines = File.ReadLines(dirConta).ToArray();

                  for (int i = 0; i < lines.Length; i++)
                  {

                  string parts = lines[i].Split(new char { '|' });
                  if (parts[0] == Users.user)
                  {
                  lines[i] = lines[i].Remove(lines[i].Length - 5);
                  lines[i] = lines[i] + "12345";
                  }

                  }
                  File.WriteAllText(dirConta, string.Join("n",lines));


                  I hope this help as the other answers pointed what miss with the code.






                  share|improve this answer






























                    1














                    Just in case you want to use your code here is the tested working version just change the lines in your code related to the ones below:



                    string lines = File.ReadLines(dirConta).ToArray();

                    for (int i = 0; i < lines.Length; i++)
                    {

                    string parts = lines[i].Split(new char { '|' });
                    if (parts[0] == Users.user)
                    {
                    lines[i] = lines[i].Remove(lines[i].Length - 5);
                    lines[i] = lines[i] + "12345";
                    }

                    }
                    File.WriteAllText(dirConta, string.Join("n",lines));


                    I hope this help as the other answers pointed what miss with the code.






                    share|improve this answer




























                      1












                      1








                      1







                      Just in case you want to use your code here is the tested working version just change the lines in your code related to the ones below:



                      string lines = File.ReadLines(dirConta).ToArray();

                      for (int i = 0; i < lines.Length; i++)
                      {

                      string parts = lines[i].Split(new char { '|' });
                      if (parts[0] == Users.user)
                      {
                      lines[i] = lines[i].Remove(lines[i].Length - 5);
                      lines[i] = lines[i] + "12345";
                      }

                      }
                      File.WriteAllText(dirConta, string.Join("n",lines));


                      I hope this help as the other answers pointed what miss with the code.






                      share|improve this answer















                      Just in case you want to use your code here is the tested working version just change the lines in your code related to the ones below:



                      string lines = File.ReadLines(dirConta).ToArray();

                      for (int i = 0; i < lines.Length; i++)
                      {

                      string parts = lines[i].Split(new char { '|' });
                      if (parts[0] == Users.user)
                      {
                      lines[i] = lines[i].Remove(lines[i].Length - 5);
                      lines[i] = lines[i] + "12345";
                      }

                      }
                      File.WriteAllText(dirConta, string.Join("n",lines));


                      I hope this help as the other answers pointed what miss with the code.







                      share|improve this answer














                      share|improve this answer



                      share|improve this answer








                      edited Nov 20 '18 at 21:20









                      maccettura

                      8,32931527




                      8,32931527










                      answered Nov 20 '18 at 21:19









                      GeorgeTGeorgeT

                      114




                      114























                          0














                          So in my opinion there are a few things wrong with this code.



                          1.) Your for-loop:



                          for(int i = 0; i < lines.Count(); i++)
                          { [...] }


                          you do not have to call ReadAllLines() again.
                          Or do:



                          foreach(string line in lines){[...]}


                          2.) Splitting into the parts:
                          Since you only have one splitting char you can call that like that:



                          string parts = lines[i].Split('|');


                          3.) Assigning the new string value:
                          Why not just do that:



                          lines[i] = $"{parts[0]}|12345";


                          4.) I would not suggest to write to the file in every loop. Just put File.WriteAllText(dirConta, lines[i]); outside your for-loop



                          5.) If you want to store data, I would strongly suggest to look into object-serialization. It makes alot of stuff easier.
                          See: Json Serialization in C#






                          share|improve this answer




























                            0














                            So in my opinion there are a few things wrong with this code.



                            1.) Your for-loop:



                            for(int i = 0; i < lines.Count(); i++)
                            { [...] }


                            you do not have to call ReadAllLines() again.
                            Or do:



                            foreach(string line in lines){[...]}


                            2.) Splitting into the parts:
                            Since you only have one splitting char you can call that like that:



                            string parts = lines[i].Split('|');


                            3.) Assigning the new string value:
                            Why not just do that:



                            lines[i] = $"{parts[0]}|12345";


                            4.) I would not suggest to write to the file in every loop. Just put File.WriteAllText(dirConta, lines[i]); outside your for-loop



                            5.) If you want to store data, I would strongly suggest to look into object-serialization. It makes alot of stuff easier.
                            See: Json Serialization in C#






                            share|improve this answer


























                              0












                              0








                              0







                              So in my opinion there are a few things wrong with this code.



                              1.) Your for-loop:



                              for(int i = 0; i < lines.Count(); i++)
                              { [...] }


                              you do not have to call ReadAllLines() again.
                              Or do:



                              foreach(string line in lines){[...]}


                              2.) Splitting into the parts:
                              Since you only have one splitting char you can call that like that:



                              string parts = lines[i].Split('|');


                              3.) Assigning the new string value:
                              Why not just do that:



                              lines[i] = $"{parts[0]}|12345";


                              4.) I would not suggest to write to the file in every loop. Just put File.WriteAllText(dirConta, lines[i]); outside your for-loop



                              5.) If you want to store data, I would strongly suggest to look into object-serialization. It makes alot of stuff easier.
                              See: Json Serialization in C#






                              share|improve this answer













                              So in my opinion there are a few things wrong with this code.



                              1.) Your for-loop:



                              for(int i = 0; i < lines.Count(); i++)
                              { [...] }


                              you do not have to call ReadAllLines() again.
                              Or do:



                              foreach(string line in lines){[...]}


                              2.) Splitting into the parts:
                              Since you only have one splitting char you can call that like that:



                              string parts = lines[i].Split('|');


                              3.) Assigning the new string value:
                              Why not just do that:



                              lines[i] = $"{parts[0]}|12345";


                              4.) I would not suggest to write to the file in every loop. Just put File.WriteAllText(dirConta, lines[i]); outside your for-loop



                              5.) If you want to store data, I would strongly suggest to look into object-serialization. It makes alot of stuff easier.
                              See: Json Serialization in C#







                              share|improve this answer












                              share|improve this answer



                              share|improve this answer










                              answered Nov 20 '18 at 21:02









                              LuchspeterLuchspeter

                              305210




                              305210























                                  0














                                  There's a few problems with your approach. First, you should try to avoid + when concatenating strings. Use $"" or string.Format instead. Second, when event-programming, it's best to write another method that the event method calls so that you can avoid blocking the UI thread with unnecessary work (like writing to a file for example). Looking at the documentation for System.IO, it's possible to iterate over the lines of text using File.ReadLines so I did that instead of reading the file twice to get the number of lines. Also, instead of using Remove and +, just use Replace; it's much easier. Finally, you need to make sure you write all the text you have. Right now, you're only writing the first line.



                                  string dirConta = $"{Environment.CurrentDirectory}/Bd/contas.txt";

                                  private async Task ModifyFileAsync()
                                  {
                                  var output = new List<string>();
                                  using (var reader = new StreamReader(dirConta))
                                  {
                                  while ((var line = await reader.ReadLineAsync().ConfigureAwait(false)) != null)
                                  {
                                  var parts = line.Split('|');
                                  if (parts[0] == Users.user)
                                  {
                                  var newLine = line.Replace(parts[1], "12345");
                                  lines.Add(newLine);
                                  }
                                  else
                                  {
                                  lines.Add(line);
                                  }
                                  }
                                  }

                                  using (var writer = new StreamWriter(dirConta))
                                  {
                                  foreach (var line in lines)
                                  {
                                  await writer.WriteLineAsync(line).ConfigureAwait(false);
                                  }
                                  }
                                  }

                                  private async void buttonGravaPass_Click(object sender, EventArgs e)
                                  {
                                  await ModifyFileAsync().ConfigureAwait(false);
                                  }





                                  share|improve this answer






























                                    0














                                    There's a few problems with your approach. First, you should try to avoid + when concatenating strings. Use $"" or string.Format instead. Second, when event-programming, it's best to write another method that the event method calls so that you can avoid blocking the UI thread with unnecessary work (like writing to a file for example). Looking at the documentation for System.IO, it's possible to iterate over the lines of text using File.ReadLines so I did that instead of reading the file twice to get the number of lines. Also, instead of using Remove and +, just use Replace; it's much easier. Finally, you need to make sure you write all the text you have. Right now, you're only writing the first line.



                                    string dirConta = $"{Environment.CurrentDirectory}/Bd/contas.txt";

                                    private async Task ModifyFileAsync()
                                    {
                                    var output = new List<string>();
                                    using (var reader = new StreamReader(dirConta))
                                    {
                                    while ((var line = await reader.ReadLineAsync().ConfigureAwait(false)) != null)
                                    {
                                    var parts = line.Split('|');
                                    if (parts[0] == Users.user)
                                    {
                                    var newLine = line.Replace(parts[1], "12345");
                                    lines.Add(newLine);
                                    }
                                    else
                                    {
                                    lines.Add(line);
                                    }
                                    }
                                    }

                                    using (var writer = new StreamWriter(dirConta))
                                    {
                                    foreach (var line in lines)
                                    {
                                    await writer.WriteLineAsync(line).ConfigureAwait(false);
                                    }
                                    }
                                    }

                                    private async void buttonGravaPass_Click(object sender, EventArgs e)
                                    {
                                    await ModifyFileAsync().ConfigureAwait(false);
                                    }





                                    share|improve this answer




























                                      0












                                      0








                                      0







                                      There's a few problems with your approach. First, you should try to avoid + when concatenating strings. Use $"" or string.Format instead. Second, when event-programming, it's best to write another method that the event method calls so that you can avoid blocking the UI thread with unnecessary work (like writing to a file for example). Looking at the documentation for System.IO, it's possible to iterate over the lines of text using File.ReadLines so I did that instead of reading the file twice to get the number of lines. Also, instead of using Remove and +, just use Replace; it's much easier. Finally, you need to make sure you write all the text you have. Right now, you're only writing the first line.



                                      string dirConta = $"{Environment.CurrentDirectory}/Bd/contas.txt";

                                      private async Task ModifyFileAsync()
                                      {
                                      var output = new List<string>();
                                      using (var reader = new StreamReader(dirConta))
                                      {
                                      while ((var line = await reader.ReadLineAsync().ConfigureAwait(false)) != null)
                                      {
                                      var parts = line.Split('|');
                                      if (parts[0] == Users.user)
                                      {
                                      var newLine = line.Replace(parts[1], "12345");
                                      lines.Add(newLine);
                                      }
                                      else
                                      {
                                      lines.Add(line);
                                      }
                                      }
                                      }

                                      using (var writer = new StreamWriter(dirConta))
                                      {
                                      foreach (var line in lines)
                                      {
                                      await writer.WriteLineAsync(line).ConfigureAwait(false);
                                      }
                                      }
                                      }

                                      private async void buttonGravaPass_Click(object sender, EventArgs e)
                                      {
                                      await ModifyFileAsync().ConfigureAwait(false);
                                      }





                                      share|improve this answer















                                      There's a few problems with your approach. First, you should try to avoid + when concatenating strings. Use $"" or string.Format instead. Second, when event-programming, it's best to write another method that the event method calls so that you can avoid blocking the UI thread with unnecessary work (like writing to a file for example). Looking at the documentation for System.IO, it's possible to iterate over the lines of text using File.ReadLines so I did that instead of reading the file twice to get the number of lines. Also, instead of using Remove and +, just use Replace; it's much easier. Finally, you need to make sure you write all the text you have. Right now, you're only writing the first line.



                                      string dirConta = $"{Environment.CurrentDirectory}/Bd/contas.txt";

                                      private async Task ModifyFileAsync()
                                      {
                                      var output = new List<string>();
                                      using (var reader = new StreamReader(dirConta))
                                      {
                                      while ((var line = await reader.ReadLineAsync().ConfigureAwait(false)) != null)
                                      {
                                      var parts = line.Split('|');
                                      if (parts[0] == Users.user)
                                      {
                                      var newLine = line.Replace(parts[1], "12345");
                                      lines.Add(newLine);
                                      }
                                      else
                                      {
                                      lines.Add(line);
                                      }
                                      }
                                      }

                                      using (var writer = new StreamWriter(dirConta))
                                      {
                                      foreach (var line in lines)
                                      {
                                      await writer.WriteLineAsync(line).ConfigureAwait(false);
                                      }
                                      }
                                      }

                                      private async void buttonGravaPass_Click(object sender, EventArgs e)
                                      {
                                      await ModifyFileAsync().ConfigureAwait(false);
                                      }






                                      share|improve this answer














                                      share|improve this answer



                                      share|improve this answer








                                      edited Nov 20 '18 at 21:13

























                                      answered Nov 20 '18 at 21:04









                                      Woody1193Woody1193

                                      2,286931




                                      2,286931






























                                          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%2f53401300%2freplacing-a-part-of-a-string-from-a-text-file%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

                                          Guess what letter conforming each word

                                          Port of Spain

                                          Run scheduled task as local user group (not BUILTIN)