Replacing a part of a string from a text file
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#
|
show 1 more comment
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#
Why callReadLines()
, then subsequently callReadAllLines()
? 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 usingFile.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 ofFile.ReadLines()
, splitting each line inside the loop, build a new string and add that to an "output" list. Then useFile.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
|
show 1 more comment
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#
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#
c#
edited Nov 20 '18 at 21:09
Joel Coehoorn
310k96495730
310k96495730
asked Nov 20 '18 at 20:50
Rui LiberalRui Liberal
185
185
Why callReadLines()
, then subsequently callReadAllLines()
? 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 usingFile.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 ofFile.ReadLines()
, splitting each line inside the loop, build a new string and add that to an "output" list. Then useFile.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
|
show 1 more comment
Why callReadLines()
, then subsequently callReadAllLines()
? 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 usingFile.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 ofFile.ReadLines()
, splitting each line inside the loop, build a new string and add that to an "output" list. Then useFile.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
|
show 1 more comment
5 Answers
5
active
oldest
votes
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
add a comment |
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);
}
}
}
Just so you are aware,File.ReadLines()
uses aStreamReader
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
add a comment |
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.
add a comment |
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#
add a comment |
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);
}
add a comment |
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
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
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
add a comment |
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
add a comment |
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
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
edited Nov 20 '18 at 21:27
answered Nov 20 '18 at 21:10
maccetturamaccettura
8,32931527
8,32931527
add a comment |
add a comment |
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);
}
}
}
Just so you are aware,File.ReadLines()
uses aStreamReader
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
add a comment |
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);
}
}
}
Just so you are aware,File.ReadLines()
uses aStreamReader
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
add a comment |
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);
}
}
}
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);
}
}
}
answered Nov 20 '18 at 21:04
blaze_125blaze_125
1,8871516
1,8871516
Just so you are aware,File.ReadLines()
uses aStreamReader
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
add a comment |
Just so you are aware,File.ReadLines()
uses aStreamReader
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
add a comment |
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.
add a comment |
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.
add a comment |
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.
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.
edited Nov 20 '18 at 21:20
maccettura
8,32931527
8,32931527
answered Nov 20 '18 at 21:19
GeorgeTGeorgeT
114
114
add a comment |
add a comment |
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#
add a comment |
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#
add a comment |
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#
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#
answered Nov 20 '18 at 21:02
LuchspeterLuchspeter
305210
305210
add a comment |
add a comment |
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);
}
add a comment |
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);
}
add a comment |
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);
}
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);
}
edited Nov 20 '18 at 21:13
answered Nov 20 '18 at 21:04
Woody1193Woody1193
2,286931
2,286931
add a comment |
add a comment |
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.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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
Why call
ReadLines()
, then subsequently callReadAllLines()
? 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 useFile.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