Deleting text from file - c#

How can I delete text from text file? For example I have some text and every time I would change the text box text in a file will change. This is what I mean:
StreamWriter = sw;
StreamReader = sr;
string path = "file.txt";
string text = txtText.Text;
if(!File.Exists(path))
{
sw = File.CreateText(path)
}
else
{
sw = new StreamWriter(path, true)
}
//here I want to delete previous line
sw.WriteLine(text)
sw.Close()

you have to replace
sw = new StreamWriter(path, true)
with
sw = new StreamWriter(path, false)
since boolean parameter defines append new text or not
and I recommend to use using to dispose the resource after using
if (!File.Exists(path))
{
sw = File.CreateText(path);
}
else
{
sw = new StreamWriter(path, false);
}
using (sw)
{
sw.WriteLine(text);
};

Related

Could not find a part of the path (Write file html)

I need to create html file and save to drive C:/TMP after i public it error
Could not find a part of the path 'C:\TMP\test.html'
I have the following code
string fileName = #"C:\\TMP\\test.html";
using (FileStream fs = File.Create(fileName))
{
using (StreamWriter w = new StreamWriter(fs, Encoding.UTF8))
{
w.WriteLine("<!DOCTYPE html>");
w.WriteLine("<html>");
w.WriteLine("<head>");
w.WriteLine("<title>PChart</title>");
w.WriteLine("</p>");
w.WriteLine("</body>");
w.WriteLine("</html>");
}
}
Are you sure the directory exists ? Put Directory.CreateDirectory in our code:
string fileName = #"C:\\TMP\\BlaBla\\test.html";
Directory.CreateDirectory(Path.GetDirectoryName(fileName));
using (FileStream fs = File.Create(fileName))
{
using (StreamWriter w = new StreamWriter(fs, Encoding.UTF8))
{
w.WriteLine("<!DOCTYPE html>");
w.WriteLine("<html>");
w.WriteLine("<head>");
w.WriteLine("<title>PChart</title>");
w.WriteLine("</p>");
w.WriteLine("</body>");
w.WriteLine("</html>");
}
}
I tested, for me it works
Hi pls try using below code. If there is no file It will create. But path should be correct.
string path = #"D:\\TMP\\test.html";
using (StreamWriter w = System.IO.File.AppendText(path))
{
w.WriteLine("<!DOCTYPE html>");
w.WriteLine("<html>");
w.WriteLine("<head>");
w.WriteLine("<title>PChart</title>");
w.WriteLine("</p>");
w.WriteLine("</body>");
w.WriteLine("</html>");
}

I am unable to create new .txt file using StreamWriter Class

Here is my code...
string path = Path.Combine(Environment.GetEnvironmentVariable("USERPROFILE"), "Music", "stream.txt");
StreamWriter sw = new StreamWriter("stream.txt");
sw.WriteLine("i am stream");
sw.Close();
You almost had the solution there:
string path = Path.Combine(Environment.GetEnvironmentVariable("USERPROFILE"),"Music", "stream.txt");
StreamWriter sw = new StreamWriter(path);
sw.WriteLine("i am stream");
sw.Close();
You just had to use the path variable you created :)
After execution remember to look in the Music folder for the stream.txt file
Check This one:-
using System;
using System.IO;
class Test
{
public static void Main()
{
string path = #"c:\temp\MyTest.txt";
if (!File.Exists(path))
{
// Create a file to write to.
using (StreamWriter sw = File.CreateText(path))
{
sw.WriteLine("Hello");
sw.WriteLine("And");
sw.WriteLine("Welcome");
}
}
// Open the file to read from.
using (StreamReader sr = File.OpenText(path))
{
string s = "";
while ((s = sr.ReadLine()) != null)
{
Console.WriteLine(s);
}
}
}
}
Reference

Read and overwrite at the same FileStream

I'm using a FileStream to lock the File to be not writeable for other processes and also read and write to it, I'm using following method for it:
public static void ChangeOrAddLine(string newLine, string oldLine = "")
{
string filePath = "C:\\test.txt";
FileMode fm = FileMode.Create;
//FileMode fm = FileMode.OpenOrCreate;
using (FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite, FileShare.Read))
using (StreamReader sr = new StreamReader(fs))
using (StreamWriter sw = new StreamWriter(fs))
{
List<string> lines = sr.ReadToEnd().Split(new string[] { "\r\n" }, StringSplitOptions.None).ToList();
bool lineFound = false;
if (oldLine != "")
for (int i = 0; i < lines.Count; i++)
if (lines[i] == oldLine)
{
lines[i] = newLine;
lineFound = true;
break;
}
if (!lineFound)
lines.Add(newLine);
sw.Write(string.Join("\r\n", lines));
}
}
I want to overwrite it with the new content but i don't find the right FileMode, using FileMode.OpenOrCreate just appends the new content to the old and FileMode.Create deletes the file-content at the time, the FileStream fm has been initialized, so the file is empty.
I need to just clear the old content at the moment, when i write the new content to it without losing the write-lock on it during the method is running.
OpenOrCreate just appends ...
Because you don't reposition after the reading.
That also shows the main problem with your approach: The FileStream only has one Position, and the Reader and the Writer heavily use caching.
However, as long as you want to replace everything and really need that locking scheme:
using (FileStream fs = new FileStream(filePath,
FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read))
{
using (StreamReader sr = new StreamReader(fs))
{
... // all the reading
}
fs.Position = 0;
using (StreamWriter sw = new StreamWriter(fs))
{
sw.Write(string.Join("\r\n", lines));
}
fs.SetLength(fs.Position); // untested, something along this line
}
and maybe you have to convince the sw and sr to leave their stream open.
But I have to note that the FileShare.Read flag doesn't make too much sense in this scenario. A reader could see al sorts of inconsistent data, including torn lines and broken UTF8 characters.

Output file wrong charset

i want to copy all lines from text a that contain a certain text to file b with a small c# application.
It's already working, but the output file doesn't show special characters like "äöü". I already tried to set the charset to utf-8, but its not working.
Here's my function:
void BtnCnvClick(object sender, EventArgs e)
{
if(File.Exists(txSource.Text)) {
string[] srcFile = File.ReadAllLines(txSource.Text, System.Text.Encoding.UTF8);
StreamWriter w = new StreamWriter(new FileStream(txOut.Text, FileMode.Open, FileAccess.ReadWrite), System.Text.Encoding.UTF8);
for(int i=0; i < srcFile.Length;i++) {
//progressBar1.Value = i/srcFile.Length;
if(i==0&&useHead) {
w.WriteLine(srcFile[i]);
} else {
if(srcFile[i].Contains(txFilter.Text)) {
w.WriteLine(srcFile[i]);
}
}
}
w.Close();
MessageBox.Show("Export successful!");
}
else MessageBox.Show("Please input a valid file name and filter.");
}
// Edit: It's working now, i just had to change it from UTF-8 to Encoding.Default!
Change this:
StreamWriter w = new StreamWriter(new FileStream(txOut.Text, FileMode.Open, FileAccess.ReadWrite), System.Text.Encoding.UTF8);
to this:
StreamWriter w = new StreamWriter(new FileStream(txOut.Text, FileMode.Open, FileAccess.ReadWrite), System.Text.Encoding.Default);

How to write into an existing textfile in windows phone?

If this is the code in opening a textfile "word.txt" in my solution explorer.
Stream txtStream = Application.GetResourceStream(new Uri("/sample;component/word.txt", UriKind.Relative)).Stream;
using (StreamReader sr = new StreamReader(txtStream))
{
string jon;
while (!sr.EndOfStream)
{
jon = sr.ReadLine();
mylistbox.ItemSource = jon;
}
}
How do i write and append in the existing textfile?
Here is an example
public static void WriteBackgroundSetting(string currentBackground)
{
const string fileName = "RecipeHub.txt";
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
if(myIsolatedStorage.FileExists(fileName))
myIsolatedStorage.DeleteFile(fileName);
var stream = myIsolatedStorage.CreateFile(fileName);
using (StreamWriter isoStream = new StreamWriter(stream))
{
isoStream.WriteLine(currentBackground);
}
}
}

Categories