How to save data from C# in a txt file? - c#

I'm new to programming and face some difficulties. I hope to save the data I'm generating (a WPF DataGrid) into a text file.
This is what I currently have:
MainWindow.xaml.cs:
private void SaveButton_Click(object sender, RoutedEventArgs e)
{
string fileName = #"D:\projects\PersonInfos\Files\PersonInfos_Copy.txt";
PersonInfosTable.ConvertToTXTFile(fileName);
}
PersonInfosTable.cs:
public void ConvertToTXTFile(string fileName)
{
StringBuilder sb = new StringBuilder();
System.Text.Encoding Output = null;
Output = System.Text.Encoding.Default;
foreach (PersonInfos personinfos in PersonInfoDetails)
{
if (PersonInfos.SelectCheckBox == true)
{
string line = String.Format("L§" + personinfos.FirstName + "§" + personinfos.LastName + "§");
sb.AppendLine(line);
StreamWriter file = new StreamWriter(fileName);
file.WriteLine(sb);
file.Close();
}
}
}
Unfortunately, this doesn't work. PersonInfosDetails is of type ObservationCollections<T> and SelectCheckBox is the check box selected by the user, and indicates which files the user wants to save.
Any ideas or suggestions? I'd appreciate your help so much and thank you so much for your time!

It is not clear what is the SelectCheckBox property. However, you need to move the writing part of your program outside the loop. Inside the loop just add every person info to your StringBuilder instance.
public void ConvertToTXTFile(string fileName)
{
StringBuilder sb = new StringBuilder();
System.Text.Encoding Output = System.Text.Encoding.Default;
foreach (PersonInfos personinfos in PersonInfoDetails)
{
// Collect every personinfos selected in the stringbuilder
if (personinfos.SelectCheckBox == true)
{
string line = String.Format("L§" + personinfos.FirstName + "§" + personinfos.LastName + "§");
sb.AppendLine(line);
}
}
// Now write the content of the StringBuilder all together to the output file
File.WriteAllText(filename, sb.ToString())
}

Have you tried How to: Write to a Text File (C# Programming Guide)?
Also, the code you've supplied won't work unless SelectCheckBox is a static property of the PersonInfos class. You'll probably have to change the if statement to
if (personInfos.SelectCheckBox == true)
{
// ...
}

Related

c# read/store data in a file?

What I want to do is actually have my program open up and set a string array so that i can use it for if commands (its used to block people) and I want to store another string in there so that it can be saved and still be used if the program restart. Can someone show me how to do this? Please and thank you :]
You could use the following:
string[] lines = File.ReadAllLines(#"Path here").ToArray();
This splits each line up into the array.
As for saving to file, google "saving to file in c#", you will get plenty of results and tutorials.
This is definitely better then the solution I posted first:
File.WriteAllLines(fileName, yourStringArray);
yourStringArray = File.ReadAllLines(fileName);
File.WriteAllLines
File.ReadAllLines
Below my first answer. Correct, but crap!
Something like this should work for you. Don't blame me for inaccuracy, I am not wide awake yet! ;)
{
string fileName = #"d:\temp\blacklist.txt";
char seperator = ';';
public Form1()
{
InitializeComponent();
string[] users = { "Dave", "John", "Shawn" };
//Save(users);
users = Load();
}
public string[] Load()
{
string line;
using (StreamReader sr = new StreamReader(this.fileName))
{
line = sr.ReadToEnd();
}
return line.Split(seperator);
}
public void Save(string[] users)
{
using (StreamWriter sw = new StreamWriter(this.fileName))
{
string line = string.Empty;
foreach (string user in users)
{
line += string.Format("{0}{1}", user, seperator);
}
sw.WriteLine(line);
sw.Flush();
}
}
}

C# Edit string in file - delete a character (000)

I am rookie in C#, but I need solve one Problem.
I have several text files in Folder and each text files has this structure:
IdNr 000000100
Name Name
Lastname Lastname
Sex M
.... etc...
Load all files from Folder, this is no Problem ,but i need delete "zero" in IdNr, so delete 000000 and 100 leave there. After this file save. Each files had other IdNr, Therefore, it is harder :(
Yes, it is possible each files manual edit, but when i have 3000 files, this is not good :)
Can C# one algorithm, which could this 000000 delete and leave only number 100?
Thank you All.
Vaclav
So, thank you ALL !
But in the End I have this Code :-) :
using System.IO;
namespace name
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Browse_Click(object sender, EventArgs e)
{
DialogResult dialog = folderBrowserDialog1.ShowDialog();
if (dialog == DialogResult.OK)
TP_zdroj.Text = folderBrowserDialog1.SelectedPath;
}
private void start_Click(object sender, EventArgs e)
{
try
{
foreach (string file in Directory.GetFiles(TP_zdroj.Text, "*.txt"))
{
string text = File.ReadAllText(file, Encoding.Default);
text = System.Text.RegularExpressions.Regex.Replace(text, "IdNr 000*", "IdNr ");
File.WriteAllText(file, text, Encoding.Default);
}
}
catch
{
MessageBox.Show("Warning...!");
return;
}
{
MessageBox.Show("Done");
}
}
}
}
Thank you ALL ! ;)
You can use int.Parse:
int number = int.Parse("000000100");
String withoutzeros = number.ToString();
According to your read/save file issue, do the files contain more than one record, is that the header or does each record is a list of key and value like "IdNr 000000100"? It's difficult to answer without these informations.
Edit: Here's a simple but efficient approach which should work if the format is strict:
var files = Directory.EnumerateFiles(path, "*.txt", SearchOption.TopDirectoryOnly);
foreach (var fPath in files)
{
String[] oldLines = File.ReadAllLines(fPath); // load into memory is faster when the files are not really huge
String key = "IdNr ";
if (oldLines.Length != 0)
{
IList<String> newLines = new List<String>();
foreach (String line in oldLines)
{
String newLine = line;
if (line.Contains(key))
{
int numberRangeStart = line.IndexOf(key) + key.Length;
int numberRangeEnd = line.IndexOf(" ", numberRangeStart);
String numberStr = line.Substring(numberRangeStart, numberRangeEnd - numberRangeStart);
int number = int.Parse(numberStr);
String withoutZeros = number.ToString();
newLine = line.Replace(key + numberStr, key + withoutZeros);
newLines.Add(line);
}
newLines.Add(newLine);
}
File.WriteAllLines(fPath, newLines);
}
}
Use TrimStart
var trimmedText = number.TrimStart('0');
This should do it. It assumes your files have a .txt extension, and it removes all occurrences of "000000" from each file.
foreach (string fileName in Directory.GetFiles("*.txt"))
{
File.WriteAllText(fileName, File.ReadAllText(fileName).Replace("000000", ""));
}
These are the steps you would want to take:
Loop each file
Read file line by line
for each line split on " " and remove leading zeros from 2nd element
write the new line back to a temp file
after all lines processed, delete original file and rename temp file
do next file
(you can avoid the temp file part by reading each file in full into memory, but depending on your file sizes this may not be practical)
You can remove the leading zeros with something like this:
string s = "000000100";
s = s.TrimStart('0');
Simply, read every token from the file and use this method:
var token = "000000100";
var result = token.TrimStart('0');
You can write a function similar to this one:
static IEnumerable<string> ModifiedLines(string file) {
string line;
using(var reader = File.OpenText(file)) {
while((line = reader.ReadLine()) != null) {
string[] tokens = line.Split(new char[] { ' ' });
line = string.Empty;
foreach (var token in tokens)
{
line += token.TrimStart('0') + " ";
}
yield return line;
}
}
}
Usage:
File.WriteAllLines(file, ModifiedLines(file));

Retrieve the data from Text File

I have a little project. What I am doing is, taking inputs from users and saving it in a text file. Its working good.
private void btbsave_Click(object sender, EventArgs e)
{
//Create Directory
DirectoryInfo dd = new DirectoryInfo("C://Program Files/UserInfo");
dd.Create();
//To save the inputs
StreamWriter sw = new StreamWriter("C://Program Files/UserInfo/UserInfo.txt", true);
sw.WriteLine(txtname.Text);
sw.WriteLine(txtage.Text);
sw.Flush();
sw.Close();
//Conformation
MessageBox.Show("Credentials Saved");
//To Clear the text box after data saved
txtname.Text = string.Empty;
txtage.Text = string.Empty;
//Focus
txturl.Focus();
}
And now, I want to retrieve the data depending on the inputs. This part is difficult for me, can you guys help me out?
private void btnsearch_Click(object sender, EventArgs e)
{
StreamReader sr = new StreamReader("C://Program Files/UserInfo/UserInfo.txt");
String mystring = sr.ReadToEnd();
//No idea how to retrive now plz help!
}
Brief description of my project:
Take some values from users like UserName and Age. Save them in a text file.
I need to retrieve values based on user UserName. I should then get UserName along with his Age and insert these values into 2 different readonly text boxes.
Personally I'd advise you to rethink your approach, but here's what you're looking for:
string sUserToSearch = "username";
string sAgeToSearch = "22";
string[] readText = File.ReadAllLines("UserInfo.txt");
for (int i = 0; i < readText.count-2; i++) {
if(readText[i] == sUserToSearch && readText[i+1] == sAgeToSearch);
// Found it!
}
I don't know what you're trying to do, but if I got you correct, you should read more on Serialization
First you have to seperate your data at the time, you insert them to your textfile
private void WriteUserToFile(User user, string path)
{
using(var sw = new StreamWriter(path, true))
{
sw.WriteLine(user.Name + ";" + user.Age);
}
}
Now you have a file like this:
User1;10
User2;20
User3;45
Now you have the possibility to split your data:
private IEnumerable<User> ReadUsersFromTextFile(string path)
{
var users = new List<User>();
using(var sr = new StringReader(path)
{
do
{
var strings = sr.ReadLine().split(';');
var user = new User();
user.Name = strings[0];
user.Age = strings[1];
users.Add(user);
}while(!sr.EndOfStream)
}
return users;
}

Delete Lines in a textfile

Hi I have a text file with table schema and data when user checks not schema required then i need to delete schema and leave the data . I am using StreamReader to read the file and checking one condition and it should delete all the lines in the file till it satisfies my condition .
Let say if i am checking
using (StreamReader tsr = new StreamReader(targetFilePath))
{
do
{
string textLine = tsr.ReadLine() + "\r\n";
{
if (textLine.StartsWith("INSERT INTO"))
{
// It should leave these lines
// and no need to delete lines
}
else
{
// it should delete the lines
}
}
}
while (tsr.Peek() != -1);
tsr.Close();
Please suggest me how to delete lines and note if textline finds "InsertInto" it should not delete any content from there .
Use a second file where to put only required lines, and, at the end of the process, remove original file and rename new one to target file.
using (StreamReader tsr = new StreamReader(targetFilePath))
{
using (StreamWriter tsw = File.CreateText(targetFilePath+"_temp"))
{
string currentLine;
while((currentLine = tsr.ReadLine()) != null)
{
if(currentLine.StartsWith("A long time ago, in a far far away galaxy ..."))
{
tsw.WriteLine(currentLine);
}
}
}
}
File.Delete(targetFilePath);
File.Move(targetFilePath+"_temp",targetFilePath);
You could use Linq:
File.WriteAllLines(targetFilePath, File.ReadAllLines(targetFilePath).Where(x => x.StartsWith("INSERT INTO")));
You read in the file just the same way you were doing. However, if the line doesn't contain what you are looking for, you simply skip it. In the end, whatever data you are left over with you then write to a new text file.
private void button1_Click(object sender, EventArgs e)
{
StringBuilder newText = new StringBuilder();
using (StreamReader tsr = new StreamReader(targetFilePath))
{
do
{
string textLine = tsr.ReadLine() + "\r\n";
{
if (textLine.StartsWith("INSERT INTO"))
{
newText.Append(textLine + Environment.NewLine);
}
}
}
while (tsr.Peek() != -1);
tsr.Close();
}
System.IO.TextWriter w = new System.IO.StreamWriter(#"C:\newFile.txt");
w.Write(newText.ToString());
w.Flush();
w.Close();
}

Delete specific line from a text file?

I need to delete an exact line from a text file but I cannot for the life of me workout how to go about doing this.
Any suggestions or examples would be greatly appreciated?
Related Questions
Efficient way to delete a line from a text file (C#)
If the line you want to delete is based on the content of the line:
string line = null;
string line_to_delete = "the line i want to delete";
using (StreamReader reader = new StreamReader("C:\\input")) {
using (StreamWriter writer = new StreamWriter("C:\\output")) {
while ((line = reader.ReadLine()) != null) {
if (String.Compare(line, line_to_delete) == 0)
continue;
writer.WriteLine(line);
}
}
}
Or if it is based on line number:
string line = null;
int line_number = 0;
int line_to_delete = 12;
using (StreamReader reader = new StreamReader("C:\\input")) {
using (StreamWriter writer = new StreamWriter("C:\\output")) {
while ((line = reader.ReadLine()) != null) {
line_number++;
if (line_number == line_to_delete)
continue;
writer.WriteLine(line);
}
}
}
The best way to do this is to open the file in text mode, read each line with ReadLine(), and then write it to a new file with WriteLine(), skipping the one line you want to delete.
There is no generic delete-a-line-from-file function, as far as I know.
One way to do it if the file is not very big is to load all the lines into an array:
string[] lines = File.ReadAllLines("filename.txt");
string[] newLines = RemoveUnnecessaryLine(lines);
File.WriteAllLines("filename.txt", newLines);
Hope this simple and short code will help.
List linesList = File.ReadAllLines("myFile.txt").ToList();
linesList.RemoveAt(0);
File.WriteAllLines("myFile.txt"), linesList.ToArray());
OR use this
public void DeleteLinesFromFile(string strLineToDelete)
{
string strFilePath = "Provide the path of the text file";
string strSearchText = strLineToDelete;
string strOldText;
string n = "";
StreamReader sr = File.OpenText(strFilePath);
while ((strOldText = sr.ReadLine()) != null)
{
if (!strOldText.Contains(strSearchText))
{
n += strOldText + Environment.NewLine;
}
}
sr.Close();
File.WriteAllText(strFilePath, n);
}
You can actually use C# generics for this to make it real easy:
var file = new List<string>(System.IO.File.ReadAllLines("C:\\path"));
file.RemoveAt(12);
File.WriteAllLines("C:\\path", file.ToArray());
This can be done in three steps:
// 1. Read the content of the file
string[] readText = File.ReadAllLines(path);
// 2. Empty the file
File.WriteAllText(path, String.Empty);
// 3. Fill up again, but without the deleted line
using (StreamWriter writer = new StreamWriter(path))
{
foreach (string s in readText)
{
if (!s.Equals(lineToBeRemoved))
{
writer.WriteLine(s);
}
}
}
Read and remember each line
Identify the one you want to get rid
of
Forget that one
Write the rest back over the top of
the file
I cared about the file's original end line characters ("\n" or "\r\n") and wanted to maintain them in the output file (not overwrite them with what ever the current environment's char(s) are like the other answers appear to do). So I wrote my own method to read a line without removing the end line chars then used it in my DeleteLines method (I wanted the option to delete multiple lines, hence the use of a collection of line numbers to delete).
DeleteLines was implemented as a FileInfo extension and ReadLineKeepNewLineChars a StreamReader extension (but obviously you don't have to keep it that way).
public static class FileInfoExtensions
{
public static FileInfo DeleteLines(this FileInfo source, ICollection<int> lineNumbers, string targetFilePath)
{
var lineCount = 1;
using (var streamReader = new StreamReader(source.FullName))
{
using (var streamWriter = new StreamWriter(targetFilePath))
{
string line;
while ((line = streamReader.ReadLineKeepNewLineChars()) != null)
{
if (!lineNumbers.Contains(lineCount))
{
streamWriter.Write(line);
}
lineCount++;
}
}
}
return new FileInfo(targetFilePath);
}
}
public static class StreamReaderExtensions
{
private const char EndOfFile = '\uffff';
/// <summary>
/// Reads a line, similar to ReadLine method, but keeps any
/// new line characters (e.g. "\r\n" or "\n").
/// </summary>
public static string ReadLineKeepNewLineChars(this StreamReader source)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
char ch = (char)source.Read();
if (ch == EndOfFile)
return null;
var sb = new StringBuilder();
while (ch != EndOfFile)
{
sb.Append(ch);
if (ch == '\n')
break;
ch = (char)source.Read();
}
return sb.ToString();
}
}
Are you on a Unix operating system?
You can do this with the "sed" stream editor. Read the man page for "sed"
What?
Use file open, seek position then stream erase line using null.
Gotch it? Simple,stream,no array that eat memory,fast.
This work on vb.. Example search line culture=id where culture are namevalue and id are value and we want to change it to culture=en
Fileopen(1, "text.ini")
dim line as string
dim currentpos as long
while true
line = lineinput(1)
dim namevalue() as string = split(line, "=")
if namevalue(0) = "line name value that i want to edit" then
currentpos = seek(1)
fileclose()
dim fs as filestream("test.ini", filemode.open)
dim sw as streamwriter(fs)
fs.seek(currentpos, seekorigin.begin)
sw.write(null)
sw.write(namevalue + "=" + newvalue)
sw.close()
fs.close()
exit while
end if
msgbox("org ternate jua bisa, no line found")
end while
that's all..use #d

Categories