Unable to replace string from text file [duplicate] - c#

This question already has answers here:
How to find and replace text in a file
(7 answers)
Closed 4 years ago.
The code I'm trying to write is to replace a string of words within a text file. Though I'm able to read the file's content to console, I'm unable to replace the string of words and write a new string to the file.
Here's my code:
private static void filesys_created (object sender, FileSystemEventArgs e)
{
using (StreamReader sr = new StreamReader(e.FullPath))
{
Console.WriteLine(sr.ReadToEnd());
File.ReadAllText(e.FullPath);
sr.Close();
}
using (StreamWriter sw = new StreamWriter(e.FullPath))
{
string text = e.FullPath.Replace("The words I want to replace");
string newtext = "text I want it to be replaced with";
sw.Write(e.FullPath, text);
sw.Write(newtext);
sw.Close();
}
}
The problem is that the .Replace is deleting everything in the text file and only inserting the path of the directory.

Well, the problems as I see it are a) you're reading the file but not assigning the text to a variable b) you're not actually doing a replace and c) you are indeed writing the file name to the output.
You don't need to use streams so your code can be simplified to this:
var contents = File.ReadAllText(e.FullPath);
contents = contents.Replace(text, newText);
File.WriteAllText(e.FullPath, contents);
It looks like you're using a FileSystemWatcher to pick up the file, so just noting that this will fire (at least) a Changed event.

You are writing the FullPath into the file, try this:
var text = null;
using (StreamReader sr = new StreamReader(e.FullPath))
{
text = sr.ReadToEnd();
Console.WriteLine(text);
}
using (StreamWriter sw = new StreamWriter(e.FullPath))
{
var replaced = text.Replace("The words I want to replace", "text I want it to be replaced with");
sw.Write(replaced);
}

Related

How to write to an existing txt file c# [duplicate]

This question already has answers here:
Open existing file, append a single line
(9 answers)
Closed 4 years ago.
I have created some code which creates a txt file with an initial text, however when I try to call the method again with a new msg it does not add it to the txt file. Below is my code:
string example = "test";
WriteToLgo(example);
public static void WriteToLog(String inputtext)
{
string location= #"C:\Users\";
string NameOfFile = "test.txt";
string fileName= String.Format("{0:yyyy-MM-dd}__{1}", DateTime.Now, NameOfFile);
string path= Path.Combine(location, fileName);
using (StreamWriter sr= File.CreateText(path))
{
sr.WriteLine(inputtext);
}
}
If I try and call the method a second time the new msg does not get added. Any help will be appreciated.
You should not use File.CreateText, but this StreamWriter overload instead:
//using append = true
using (StreamWriter sr = new StreamWriter(path, true))
{
sr.WriteLine(inputtext);
}
See MSDN
The File.CreateText only creates a new file each time, overwriting anything in it. Does not append to existing files.
You should use either File.AppendText(...) to open your existing file for appending content, or use the base StreamWriter class to open it with append options
Something like:
using (StreamWriter sr = File.AppendText(path))
{
sr.WriteLine(inputtext);
}
If you use the base StreamWriter class instead of File.AppendText you can use it like StreamWriter sr = new StreamWriter(path, true); HOWEVER, you must check to see if the file exists before open it for append. Probably reccomend the File.AppendText in your case.

Append Text at exact location in text

I was looking to append text to a exact location in a text file. I have used StreamReader to find the text in the file I am looking for. I thought about using StreamWriter but that obviously doesn't make sense. I was hoping to find some "append" method in some class somewhere that would help me do this but with now success. Or is there a better way to do this than to use StreamReader?
using (StreamReader sr = new StreamReader(fileName))
{
string line;
while ((line = sr.ReadLine()) != null)
{
if (line.Contains("VAR_GLOBAL CONSTANT"))
{
//append text before this variable
// e.g. (*VAR_GLOBAL CONSTANT
// append the (* before VAR_GLOBAL CONSTANT
}
if (line.Contains("END_VAR"))
{
//append text after this variable
// e.g. END_VAR*)
// append the *) after END_VAR
}
}
}
Does anyone have any thoughts on how to accomplish this?
One way to do it would be to read the file contents into a string, update the contents locally, and then write it back to the file again. This probably isn't very feasible for really large files, especially if the appending is done at the end, but it's a start:
var filePath = #"f:\public\temp\temp.txt";
var appendBeforeDelim = "VAR_GLOBAL CONSTANT";
var appendAfterDelim = "END_VAR";
var appendBeforeText = "Append this string before some text";
var appendAfterText = "Append this string after some text";
var newFileContents = File.ReadAllText(filePath)
.Replace(appendBeforeDelim, $"{appendBeforeText}{appendBeforeDelim}")
.Replace(appendAfterDelim, $"{appendAfterDelim}{appendAfterText}");
File.WriteAllText(filePath, newFileContents);

How do you in C# read a text file for a specific string, and if it doesnt exist write it

I know how to read append and write with Streamreader/Steamwriter. But I am having issues with getting my program to read the text file and check for a specific string of data. If it doesnt exist write it at the end. Any Ideas? Im trying to do this to a specific file, via web page button using Server.MapPath.
This how you read file and check
using (StreamReader sr = new StreamReader(path));
{
string contents = sr.ReadToEnd();
if (contents.Contains(//string to check//))
{
appendtofile("add string")
}
}
and here is how you append
public void appendtofile(string text)
{
using (StreamWriter sw = File.AppendText(path))
{
sw.WriteLine(text);
}
}

C# - Appending text files

I have code that reads a file and then converts it to a string, the string is then written to a new file, although could someone demonstrate how to append this string to the destination file (rather than overwriting it)
private static void Ignore()
{
System.IO.StreamReader myFile =
new System.IO.StreamReader("c:\\test.txt");
string myString = myFile.ReadToEnd();
myFile.Close();
Console.WriteLine(myString);
// Write the string to a file.
System.IO.StreamWriter file = new System.IO.StreamWriter("c:\\test2.txt");
file.WriteLine(myString);
file.Close();
}
If the file is small, you can read and write in two code lines.
var myString = File.ReadAllText("c:\\test.txt");
File.AppendAllText("c:\\test2.txt", myString);
If the file is huge, you can read and write line-by-line:
using (var source = new StreamReader("c:\\test.txt"))
using (var destination = File.AppendText("c:\\test2.txt"))
{
var line = source.ReadLine();
destination.WriteLine(line);
}
using(StreamWriter file = File.AppendText(#"c:\test2.txt"))
{
file.WriteLine(myString);
}
Use File.AppendAllText
File.AppendAllText("c:\\test2.txt", myString)
Also to read it, you can use File.ReadAllText to read it. Otherwise use a using statement to Dispose of the stream once you're done with the file.
Try
StreamWriter writer = File.AppendText("C:\\test.txt");
writer.WriteLine(mystring);

get the value of notepad and put it inside the c# string?

Notepad:
Hello world!
How I'll put it in C# and convert it into string..?
So far, I'm getting the path of the notepad.
string notepad = #"c:\oasis\B1.text"; //this must be Hello world
Please advice me.. I'm not familiar on this.. tnx
You can read text using the File.ReadAllText() method:
public static void Main()
{
string path = #"c:\oasis\B1.txt";
try {
// Open the file to read from.
string readText = System.IO.File.ReadAllText(path);
Console.WriteLine(readText);
}
catch (System.IO.FileNotFoundException fnfe) {
// Handle file not found.
}
}
You need to read the content of the file, e.g.:
using (var reader = new StreamReader(new FileStream(path, FileMode.Open, FileAccess.Read))
{
return reader.ReadToEnd();
}
Or, as simply as possible:
return File.ReadAllText(path);
make use of StreamReader and read the file as shown below
string notepad = #"c:\oasis\B1.text";
StringBuilder sb = new StringBuilder();
using (StreamReader sr = new StreamReader(notepad))
{
while (sr.Peek() >= 0)
{
sb.Append(sr.ReadLine());
}
}
string s = sb.ToString();
Use File.ReadAllText
string text_in_file = File.ReadAllText(notepad);
check this example:
// Read the file as one string.
System.IO.StreamReader myFile =
new System.IO.StreamReader("c:\\test.txt");
string myString = myFile.ReadToEnd();
myFile.Close();
// Display the file contents.
Console.WriteLine(myString);
// Suspend the screen.
Console.ReadLine();
Reading From a Text File (Visual C#), in this example # is not used when StreamReader is being called, however when you write the code in Visual Studio it will give the below error for each \
Unrecognized escape sequence
To escape this error you can write # before " that is at the beginning of your path string.
I shoul also mentioned that it does not give this error if we use \\ even if we do not write #.
// Read the file as one string.
System.IO.StreamReader myFile = new System.IO.StreamReader(#"c:\oasis\B1.text");
string myString = myFile.ReadToEnd();
myFile.Close();
// Display the file contents.
Console.WriteLine(myString);
// Suspend the screen.
Console.ReadLine();

Categories

Resources