I am currently working on a project where i must remove a specfic line of text from a text file.
This is the code i have already:
static void Main( string[] args )
{
string line = null;
string line_to_delete = "--";
string desktopLocation = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string text = Path.Combine( desktopLocation, "tim3.txt" );
string file = Path.Combine( desktopLocation, "tim4.txt" );
using (StreamReader reader = new StreamReader( text))
{
using (StreamWriter writer = new StreamWriter(file ))
{
while((line = reader.ReadLine()) != null)
{
if (string.Compare( line, line_to_delete ) == 0)
continue;
writer.WriteLine( line );
}
}
This writes only the text to a new txt file but doesnt delete anything.
Thanks.
The main problem is that i just need to delete a specific line of text in the txt file.
I suspect leading/training spaces, which are causing String.comapre to return unexpected result
Instead of
try
As above is not working can you try following (LINQ)
EDIT – to replace only text
If above works, it will replace all using block in your code
If above does not work, i suspect it is data issue (“__” not present in text file)