Maybe I'm overthinking this. I've got a working method for writing to a text file, and reading from it.
Writing:
public void SaveNotes()
{
using (StreamWriter save= new StreamWriter("notes.txt", true))
{
foreach (var element in collection)
{
spara.Write(element.Prio+ " " + element.Note+ "\n");
}
}
}
Now I'm trying to design a method that looks for any '0' in my list, and overwrite the entire line.
Is there any easier way to tell the program that all lines containing a '0' should be overwritten with blankspaces? Any input much appreciated.
public static void Delete(Note note)
{
using (StreamWriter remove = new StreamWriter("notes.txt"))
{
Regex rgx = new Regex("");
foreach (var element in collection)
{
while (element.Notering.Contains("0"))
{
rgx.Replace(element.Note, "");
rgx.Replace(element.Prio, "");
}
}
}
}
Why don't you combine two of them?
public void SaveNotes()
{
using (StreamWriter save= new StreamWriter("notes.txt", true))
{
foreach (var element in collection)
{
if (element.Prio.IndexOf('\0') < 0 && element.Note.IndexOf('\0') < 0)
spara.Write(element.Prio+ " " + element.Note+ "\n");
else spara.Write(" \n");
}
}
}
Related
I would like to export my class in .csv file, i follow this comment : https://stackoverflow.com/a/38088636/10152334
but when i export (in Buses_Data.Buses_List), i have wrong data output, all data are on same line :
public void ExportToCSV(Buses_Data classToExport, string filepath)
{
try
{
if (File.Exists(filepath))
{
Console.WriteLine("Le fichier existe");
System.IO.File.Delete(filepath);
Console.WriteLine("l'ancien fichier à été supprimé");
}
Console.WriteLine("Export :...");
using (StreamWriter sw = new StreamWriter(filepath))
using (CsvWriter cw = new CsvWriter(sw))
{
cw.WriteHeader<Bus>();
foreach (Bus emp in classToExport.Buses_List)
{
cw.WriteRecord<Bus>(emp);
}
}
Console.WriteLine("Export CSV: OK");
}
catch (Exception i)
{
Console.WriteLine("Error ! " + i);
}
}
I don't know why the code doesn't work
Edit :
Wrong output:
Right output (Data not corresponding)
Edit 2 :
I tried this comment : Enforce LF line endings with CsvHelper
using (StreamWriter sw = new StreamWriter(filepath))
using (CsvWriter cw = new CsvWriter(sw))
{
cw.WriteHeader<Bus>();
foreach (Bus emp in classToExport.Buses_List)
{
cw.WriteRecord<Bus>(emp);
sw.NewLine = "\n";
cw.NextRecord();
}
}
I have better result but i Bus N°1 is on first line, not in second line
Solution :
using (StreamWriter sw = new StreamWriter(filepath))
using (CsvWriter cw = new CsvWriter(sw))
{
cw.WriteHeader<Bus>();
cw.NextRecord();
foreach (Bus emp in classToExport.Buses_List)
{
cw.WriteRecord<Bus>(emp);
//sw.NewLine = "\n";
cw.NextRecord();
}
}
Based on answer of GitHub issue, written by Josh Close:
You need to call NextRecord() when you're done writing the header.
This is so you can write more fields manually before or after.
I tried it, it works well.
Have you tried CsvWriter.NextRecord?
foreach (Bus emp in classToExport.Buses_List)
{
cw.WriteRecord<Bus>(emp);
cw.NextRecord();
}
I try to detect quotes in a loaded text file but it is not working. I have tried with '"' and '\"' without success. Any suggestion? thanks
void read()
{
txt = File.ReadAllText("txt/txttst");
for(int i=0;i<txt.Length;i++)
{
if(txt[i]=='"')
{
Debug.Log("Quotes at "+i);
}
}
}
How about this
string[] lines = File.ReadAllLines(#"txt/txttst");
for (int i=0;i<lines.Length;i++)
{
string line = lines[i];
// ASCII Code of Quotes is 34
var bytes = Encoding.UTF8.GetBytes(line.ToCharArray()).ToList();
if(bytes.Count(b=> b.ToString()=="34")>0)
Console.WriteLine("\"" + "at line " + (i + 1));
}
This is how you can do it, please see the code and screenshot below. Hope it helps.
namespace TestConsoleApp
{
class Program
{
static void Main(string[] args)
{
string txt = File.ReadAllText(#"C:\Users\Public\TestFolder\test.txt");
string[] lines = File.ReadAllLines(#"C:\Users\Public\TestFolder\test.txt");
var reg = new Regex("\"");
Console.WriteLine("Contents of test.txt are; ");
foreach (string line in lines)
{
Console.WriteLine(line);
var matches = reg.Matches(line);
foreach (var item in matches)
{
Console.WriteLine("Quotes at "+ ((System.Text.RegularExpressions.Capture)item).Index);
}
}
}
}
}
Ok I found the problem, my text editor did a subtle auto-correct from " to “ . Cheers.
I need to check certain columns of data to make sure there are no trailing blank spaces. At first thought I thought it would be very easy, but after attempting to achieve the goal I have got stuck.
I know that there should be 6-digits in the column I need to check. If there is less I will reject, if there are more I will trim the blank spaces. After doing that for the entire file, I want to write it back to the file with the same delimiters.
This is my attempt:
Everything seems to be working correctly except for writing the file.
if (File.Exists(filename))
{
using (StreamReader sr = new StreamReader(filename))
{
string lines = sr.ReadLine();
string[] delimit = lines.Split('|');
while (delimit[count] != "COLUMN_DATA_TO_CHANGE")
{
count++;
}
string[] allLines = File.ReadAllLines(#filename);
foreach(string nextLine in allLines.Skip(1)){
string[] tempLine = nextLine.Split('|');
if (tempLine[count].Length == 6)
{
checkColumn(tempLine);
writeFile(tempLine);
}
else if (tempLine[count].Length > 6)
{
tempLine[count] = tempLine[count].Trim();
checkColumn(tempLine);
}
else
{
throw new Exception("Not enough numbers");
}
}
}
}
}
public static void checkColumn(string[] str)
{
for (int i = 0; i < str[count].Length; i++)
{
char[] c = str[count].ToCharArray();
if (!Char.IsDigit(c[i]))
{
throw new Exception("A non-digit is contained in data");
}
}
}
public static void writeFile(string[] str)
{
string temp;
using (StreamWriter sw = new StreamWriter(filename+ "_tmp", false))
{
StringBuilder builder = new StringBuilder();
bool firstColumn = true;
foreach (string value in str)
{
if (!firstColumn)
{
builder.Append('|');
}
if (value.IndexOfAny(new char[] { '"', ',' }) != -1)
{
builder.AppendFormat("\"{0}\"", value.Replace("\"", "\"\""));
}
else
{
builder.Append(value);
}
firstColumn = false;
}
temp = builder.ToString();
sw.WriteLine(temp);
}
}
If there is a better way to go about this, I would love to hear it. Thank you for looking at the question.
edit:
file structure-
country| firstname| lastname| uniqueID (column I am checking)| address| etc
USA|John|Doe|123456 |5 main street|
notice the blank space after the 6
var oldLines = File.ReadAllLines(filePath):
var newLines = oldLines.Select(FixLine).ToArray();
File.WriteAllLines(filePath, newLines);
string FixLine(string oldLine)
{
string fixedLine = ....
return fixedLine;
}
The main problem with writing the file is that you're opening the output file for each output line, and you're opening it with append=false, which causes the file to be overwritten every time. A better approach would be to open the output file one time (probably right after validating the input file header).
Another problem is that you're opening the input file a second time with .ReadAllLines(). It would be better to read the existing file one line at a time in a loop.
Consider this modification:
using (StreamWriter sw = new StreamWriter(filename+ "_tmp", false))
{
string nextLine;
while ((nextLine = sr.ReadLine()) != null)
{
string[] tempLine = nextLine.Split('|');
...
writeFile(sw, tempLine);
I am a newbie in C# I just have a doubt.I have two group boxes,each of them has three radio buttons in it,If I want to select each radio button from each groupbox and write a condition for that ,,How can I do that. Below is the code:
public void SaveMyTextBoxContents()
{
string path = usbLetter +"MSREAD.txt";
if (lbItems.SelectedIndex == -1)
{
if (rdBtnMed.Checked)
{
using (StreamWriter File = new StreamWriter(filepath))
{
foreach (string item in lbItems.Items)
{
saveAllText = medium + " " + item;
outputFile.WriteLine(saveText);
}
}
}
}
else if (rdBtnMedium.Checked && rdBtnN.Checked)
{
using (StreamWriter File = new StreamWriter(filepath))
{
foreach (string item in lbItems.Items)
{
saveAllText = mediumNo + " " + item;
outputFile.WriteLine(saveText);
}
}
}
}
}
Please help me I got stuck up with this.
Thanks Krik
Make small panels to the size of radio button pairs and place those radio buttons on them (two each). E.g separate for male, female; separate for young, old etc. The panel won't show on run. This will work Insha'Allah in a group box too.
You're brackets are off, so it only checks rdBtnMedium and rdBtnN if lblItems.SelectedIndex != 1. Here's what I think you need:
if (lbItems.SelectedIndex == -1)
{
if (rdBtnMed.Checked)
{
using (StreamWriter File = new StreamWriter(filepath))
{
foreach (string item in lbItems.Items)
{
saveAllText = medium + " " + item;
outputFile.WriteLine(saveText);
}
}
}
else if (rdBtnMedium.Checked && rdBtnN.Checked)
{
using (StreamWriter File = new StreamWriter(filepath))
{
foreach (string item in lbItems.Items)
{
saveAllText = mediumNo + " " + item;
outputFile.WriteLine(saveText);
}
}
}
}
This is whats going on. I have a huge text file that is suppose to be 1 line per entry. The issue is sometimes the line is broken with a new line.
I edit this entire file and wherever the file doesn't begin with ("\"A) i need to append the current line to the previous line ( replacing \n with " "). Everything I come up with keeps appending the line to a new line. Any help is appricated...
CODE:
public void step1a()
{
string begins = ("\"A");
string betaFilePath = #"C:\ext.txt";
string[] lines = File.ReadAllLines(betaFilePath);
foreach (string line in lines)
{
if (line.StartsWith(begins))
{
File.AppendAllText(#"C:\xt2.txt",line);
File.AppendAllText(#"C:\xt2.txt", "\n");
}
else
{
string line2 = line.Replace(Environment.NewLine, " ");
File.AppendAllText(#"C:\xt2.txt",line2);
}
}
}
Example:
Orig:
"\"A"Hero|apple|orange|for the fun of this
"\"A"Hero|apple|mango|lots of fun always
"\"A"Her|apple|fruit|no
pain is the way
"\"A"Hero|love|stackoverflowpeople|more fun
Resulting:
"\"A"Hero|apple|orange|for the fun of this
"\"A"Hero|apple|mango|lots of fun always
"\"A"Her|apple|fruit|no pain is the way
"\"A"Hero|love|stackoverflowpeople|more fun
my problem isnt the finding the if (line.StartsWith(begins)) its the else statement, it appends line2 to a new line
it seems like your string is not well formated...
try this "\"\\\"A\"" instead
public void step1a()
{
string begins = ("\"\\\"A\"");
string betaFilePath = #"C:\ext.txt";
string[] lines = File.ReadAllLines(betaFilePath);
foreach (string line in lines)
{
if (line.StartsWith(begins))
{
File.AppendAllText(#"C:\xt2.txt",line);
File.AppendAllText(#"C:\xt2.txt", "\n");
}
else
{
string line2 = line.Replace(Environment.NewLine, " ");
File.AppendAllText(#"C:\xt2.txt",line2);
}
}
}
This does what you want:
CopyFileRemovingStrayNewlines(#"C:\ext.txt", #"C:\xt2.txt", #"""\""A");
With this method:
public static void CopyFileRemovingStrayNewlines(string sourcePath, string destinationPath, string linePrefix)
{
string[] lines = File.ReadAllLines(sourcePath);
bool firstLine = true;
foreach (string line in lines)
{
if (line.StartsWith(linePrefix))
{
if (!firstLine)
File.AppendAllText(destinationPath, Environment.NewLine);
else
firstLine = false;
File.AppendAllText(destinationPath, line);
}
else
{
File.AppendAllText(destinationPath, " ");
File.AppendAllText(destinationPath, line);
}
}
}
It does have the problem of appending to an existing file, though. I suggest using a StreamWriter rather than AppendAllText. Like this:
public static void CopyFileRemovingStrayNewlines(string sourcePath, string destinationPath, string linePrefix)
{
string[] lines = File.ReadAllLines(sourcePath);
bool firstLine = true;
using (StreamWriter writer = new StreamWriter(destinationPath, false))
{
foreach (string line in lines)
{
if (line.StartsWith(linePrefix))
{
if (!firstLine)
writer.WriteLine();
else
firstLine = false;
writer.Write(line);
}
else
{
writer.Write(" ");
writer.Write(line);
}
}
}
}
Your problem is that the \ is a C# escape code.
Your string is parsed as "A, because \" is the escape code for a single ".
You should make the begins string an #-string, which does not use escape codes.
You will then need to escape the " by doubling it up.
For example:
const string begins = #"\""A";
Note that the best way to do this is to use a StreamWriter, like this:
using(StreamWriter writer = File.Create(#"C:\xt2.txt"))
{
foreach (string line in lines)
{
if (line.StartsWith(begins))
writer.WriteLine(); //Close the previous line
writer.Write(line);
}
}
Based on #SLaks's example here is some code that should do the trick:
public static void step1a()
{
string betaFilePath = #"C:\ext.txt";
string[] lines = File.ReadAllLines(betaFilePath);
using (StreamWriter writer = new StreamWriter(File.Create(#"C:\xt2.txt")))
{
string buffer = null;
foreach (string line in lines)
{
if (!line.StartsWith(begins))
{
writer.WriteLine(buffer + line);
buffer = null;
}
else
{
if (buffer != null)
writer.WriteLine(buffer);
buffer = line;
}
}
if(buffer != null)
Console.Out.WriteLine(buffer);
}
}