I have a text file that I want to read in and put each line from the file into its own string.
So the file will have 4 lines:
2017-01-20
05:59:30
+353879833382
971575 Michael
So in the code I need to read in the file and split up each line and put them into a string i.e the first line will equal to string date, second line will equal to string time etc
Code:
public static void ParseTXTFile(string FileName, int CompanyID)
{
try
{
FileInfo file = new FileInfo(FileName);
string Date;
string Time;
string Phone;
string JobNo;
string Name;
using (CsvReader reader = new CsvReader(new StreamReader(FileName), false))
{
while (reader.ReadNextRecord())
{
}
}
}
catch (Exception ex)
{
throw (ex);
}
}
How do I read in each line of the file and set it to a string?
You may want to consider using the File.ReadAllLines() method which will store each line of your file into an array :
var lines = File.ReadAllLines(FileName);
You could then access each of your properties by their indices as needed :
string Date = lines[0];
string Time = lines[1];
string Phone = lines[2];
string JobNo = lines[3];
string Name = lines[4];
Related
I would like to know how to get the filename into an array and load the filename to CSV file. For example, this is the filename, File_1_20170428101607. I want the file name (date and time format – 28/04/2017 10:16:07) to be parse into a column in the output file (csv file). This is the code for time, can you please check and how to add the time to array to be parse to csv file?
private static string[] GetFileNames(string path, string filter)
{
string fileName = #”C:\\Desktop\\File_1_20170428101607.csv”;
string result;
result = Path.GetFileName(fileName);
Console.WriteLine(“GetFileName(‘{0}’) returns ‘{1}'”,
fileName, result);
string[] files = Directory.GetFiles(path, filter);
for (int i = 0; i parsing was not possible -> return null
{
return null;
}
}
private static DateTime? ParseDateFromFilename(string filename)
{
//regex is used to extract the 14 digit timestamp from filename
var timestamp = Regex.Match(filename, #"\d{14}$");
if (!timestamp.Success)
{
//if no match was found return null
return null;
}
try
{
//try to parse the date with known timestamp and return
return DateTime.ParseExact(timestamp.Value, "yyyyMMddHHmmss", CultureInfo.InvariantCulture);
}
catch
{
//any error -> parsing was not possible -> return null
return null;
}
You can try this:
First create a StringBuilder that will contain csv content:
StringBuilder csv = new StringBuilder();
string filePath = "...";
Next create a for loop and take values for two columns and append it do StringBuilder
//for loop start
string fileName = "File_1_20170428101607";
string datePart = fileName.Split('_').Last();
DateTime dt = DateTime.ParseExact(datePart, "yyyyMMddhhmmss", null);
string dateString = dt.ToString("dd/mm/yyyy hh:MM:ss", System.Globalization.CultureInfo.InvariantCulture);
var firstColVal = fileName;
var secondColVal = dateString;
var newLine = string.Format("{0},{1}", firstColVal, secondColVal);
csv.AppendLine(newLine);
//loop end
After the for loop save StringBuilder content to your csv file:
File.WriteAllText(filePath, csv.ToString());
I'm kind of new to coding and I've been trying to replace a word in a text file but when I execute the program it gives me the "File is used by another process error"
private void btnSave1_Click(object sender, EventArgs e)
{
string DOB = dateTimePicker1.Value.ToString();
string Fname = txtBFirstName.ToString();
string Lname = txtBLastName.ToString();
string IDnum = txtBIDnum.ToString();
string Address = txtBAddress.ToString();
string nationality = txtBNationality.ToString();
//string gender = cmbGender.SelectedItem.ToString();
// string marrStatus = cmbMaritialStatus.SelectedItem.ToString();
StreamReader read = null;
//write to file
try
{
// var lines = File.ReadAllLines("CV.txt");
string line;
read = new StreamReader("CurriculumVitae.txt");
while ((line = read.ReadLine()) != null)
{
string text = File.ReadAllText("CurriculumVitae.txt");
text = text.Replace("Empty", DOB);
File.WriteAllText("CurriculumVitae.txt",
File.ReadAllText("CurriculumVitae.txt")
.Replace("empty",DOB));
}
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
}
finally
{
read.Close();
}
//Open Next Form
Education objNextForm = new Education();
objNextForm.Visible = true;
}
Problem from these 3 lines
read = new StreamReader("CurriculumVitae.txt");
string text = File.ReadAllText("CurriculumVitae.txt");
File.WriteAllText("CurriculumVitae.txt"
,File.ReadAllText("CurriculumVitae.txt").Replace("empty",DOB));
Both StreamReader and File.ReadAllText will lock a file. And whenever they try to lock same file it will error
You should try to do thing once. Don't try to open file many times. And don't open same file before it closed
You can just take out this part around your code, as you're not using the StreamReader you created:
while ((line = read.ReadLine()) != null)
{
...
}
And change
File.WriteAllText("CurriculumVitae.txt",
File.ReadAllText("CurriculumVitae.txt");
To
File.WriteAllText("CurriculumVitae.txt", text);
You will want to update your StreamReader to open the file in "shared" mode so that it doesn't lock the file.
See this question for details on how to do that.
First, don't use a StreamReader when you use File.ReadAllText as it's not needed, the other error comes from this line:
File.WriteAllText("CurriculumVitae.txt", File.ReadAllText("CurriculumVitae.txt").Replace("empty", DOB));
You are opening the same file twice, try something like this:
string content = File.ReadAllText("CurriculumVitae.txt").Replace("empty", DOB);
File.WriteAllText("CurriculumVitae.txt", content);
Use either StreamReader or ReadAllText but not both at the same time...
Also I would really suggest to do "usings" wherever possible becuase this helps a lot closing objects (but is not your prime problem here)
// It will free resources on its own.
//
using (StreamReader reader = new StreamReader("file.txt"))
{
line = reader.ReadLine();
}
Console.WriteLine(line);
}
I know this has been asked a few times, but I have seen a lot of regex etc., and I'm sure there is another way to do this with just a stream reader/writer. Below is my code. I'm trying to replace "tea" with the word "cabbage". Can somebody help? I believe I have the wrong syntax.
namespace Week_9_Exer_4
{
class TextImportEdit
{
public void EditorialControl()
{
string fileName;
string lineReadFromFile;
Console.WriteLine("");
// Ask for the name of the file to be read
Console.Write("Which file do you wish to read? ");
fileName = Console.ReadLine();
Console.WriteLine("");
// Open the file for reading
StreamReader fileReader = new StreamReader("C:\\Users\\Greg\\Desktop\\Programming Files\\story.txt");
// Read the lines from the file and display them
// until a null is returned (indicating end of file)
lineReadFromFile = fileReader.ReadLine();
Console.WriteLine("Please enter the word you wish to edit out: ");
string editWord = Console.ReadLine();
while (lineReadFromFile != null)
{
Console.WriteLine(lineReadFromFile);
lineReadFromFile = fileReader.ReadLine();
}
String text = File.ReadAllText("C:\\Users\\Greg\\Desktop\\Programming Files\\story.txt");
fileReader.Close();
StreamWriter fileWriter = new StreamWriter("C:\\Users\\Greg\\Desktop\\Programming Files\\story.txt", false);
string newText = text.Replace("tea", "cabbage");
fileWriter.WriteLine(newText);
fileWriter.Close();
}
}
}
If you don't care about memory usage:
string fileName = #"C:\Users\Greg\Desktop\Programming Files\story.txt";
File.WriteAllText(fileName, File.ReadAllText(fileName).Replace("tea", "cabbage"));
If you have a multi-line file that doesn't randomly split words at the end of the line, you could modify one line at a time in a more memory-friendly way:
// Open a stream for the source file
using (var sourceFile = File.OpenText(fileName))
{
// Create a temporary file path where we can write modify lines
string tempFile = Path.Combine(Path.GetDirectoryName(fileName), "story-temp.txt");
// Open a stream for the temporary file
using (var tempFileStream = new StreamWriter(tempFile))
{
string line;
// read lines while the file has them
while ((line = sourceFile.ReadLine()) != null)
{
// Do the word replacement
line = line.Replace("tea", "cabbage");
// Write the modified line to the new file
tempFileStream.WriteLine(line);
}
}
}
// Replace the original file with the temporary one
File.Replace("story-temp.txt", "story.txt", null);
In the end i used this : Hope it can help out others
public List<string> EditorialResponse(string fileName, string searchString, string replacementString)
{
List<string> list = new List<string>();
using (StreamReader reader = new StreamReader(fileName))
{
string line;
while ((line = reader.ReadLine()) != null)
{
line = line.Replace(searchString, replacementString);
list.Add(line);
Console.WriteLine(line);
}
reader.Close();
}
return list;
}
}
class Program
{
static void Main(string[] args)
{
TextImportEdit tie = new TextImportEdit();
List<string> ls = tie.EditorialResponse(#"C:\Users\Tom\Documents\Visual Studio 2013\story.txt", "tea", "cockrel");
StreamWriter writer = new StreamWriter(#"C:\Users\Tom\Documents\Visual Studio 2013\story12.txt");
foreach (string line in ls)
{
writer.WriteLine(line);
}
writer.Close();
}
}
}
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));
So here is my problem, I'm trying to get the content of a text file as a string, then parse it. What I want is a tab containing each word and only words (no blank, no backspace, no \n ...) What I'm doing is using a function LireFichier that send me back the string containing the text from the file (works fine because it's displayed correctly) but when I try to parse it fails and start doing random concatenation on my string and I don't get why.
Here is the content of the text file I'm using :
truc,
ohoh,
toto, tata, titi, tutu,
tete,
and here's my final string :
;tete;;titi;;tata;;titi;;tutu;
which should be:
truc;ohoh;toto;tata;titi;tutu;tete;
Here is the code I wrote (all using are ok):
namespace ConsoleApplication1{
class Program
{
static void Main(string[] args)
{
string chemin = "MYPATH";
string res = LireFichier(chemin);
Console.WriteLine("End of reading...");
Console.WriteLine("{0}",res);// The result at this point is good
Console.WriteLine("...starting parsing");
res = parseString(res);
Console.WriteLine("Chaine finale : {0}", res);//The result here is awfull
Console.ReadLine();//pause
}
public static string LireFichier(string FilePath) //Read the file, send back a string with the text
{
StreamReader streamReader = new StreamReader(FilePath);
string text = streamReader.ReadToEnd();
streamReader.Close();
return text;
}
public static string parseString(string phrase)//is suppsoed to parse the string
{
string fin="\n";
char[] delimiterChars = { ' ','\n',',','\0'};
string[] words = phrase.Split(delimiterChars);
TabToString(words);//I check the content of my tab
for(int i=0;i<words.Length;i++)
{
if (words[i] != null)
{
fin += words[i] +";";
Console.WriteLine(fin);//help for debug
}
}
return fin;
}
public static void TabToString(string[] montab)//display the content of my tab
{
foreach(string s in montab)
{
Console.WriteLine(s);
}
}
}//Fin de la class Program
}
I think your main issue is
string[] words = phrase.Split(delimiterChars, StringSplitOptions.RemoveEmptyEntries);
You could try using the string splitting option to remove empty entries for you:
string[] words = phrase.Split(delimiterChars, StringSplitOptions.RemoveEmptyEntries);
See the documentation here.
Try this:
class Program
{
static void Main(string[] args)
{
var inString = LireFichier(#"C:\temp\file.txt");
Console.WriteLine(ParseString(inString));
Console.ReadKey();
}
public static string LireFichier(string FilePath) //Read the file, send back a string with the text
{
using (StreamReader streamReader = new StreamReader(FilePath))
{
string text = streamReader.ReadToEnd();
streamReader.Close();
return text;
}
}
public static string ParseString(string input)
{
input = input.Replace(Environment.NewLine,string.Empty);
input = input.Replace(" ", string.Empty);
string[] chunks = input.Split(',');
StringBuilder sb = new StringBuilder();
foreach (string s in chunks)
{
sb.Append(s);
sb.Append(";");
}
return sb.ToString(0, sb.ToString().Length - 1);
}
}
Or this:
public static string ParseFile(string FilePath)
{
using (var streamReader = new StreamReader(FilePath))
{
return streamReader.ReadToEnd().Replace(Environment.NewLine, string.Empty).Replace(" ", string.Empty).Replace(',', ';');
}
}
Your main problem is that you are splitting on \n, but the linebreaks read from your file are \r\n.
You output string does contain all of your items, but the \r characters left in it cause later "lines" to overwrite earlier "lines" on the console.
(\r is a "return to start of line" instruction; without the \n "move to the next line" instruction your words from line 1 are being overwritten by those in line 2, then line 3 and line 4.)
As well as splitting on \r as well as \n, you need to check a string is not null or empty before adding it to your output (or, preferably, use StringSplitOptions.RemoveEmptyEntries as others have mentioned).
string ParseString(string filename) {
return string.Join(";", System.IO.File.ReadAllLines(filename).Where(x => x.Length > 0).Select(x => string.Join(";", x.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).Select(y => y.Trim()))).Select(z => z.Trim())) + ";";
}