I have a lot of .txt files with data in it. The data is separated with a ,.
In the third column the data is in the dd-mm-yyyy format. But it has to be in yyyy/mm/dd format. Changing the machine format isn't a solution.
The files are small enough to load into memory and opened on the following way, but I can't figured out how to solve the date issue. Who can help me?
foreach (string x in a)
{
string somePath = #"C:\test\";
string filename = x;
string path = Path.Combine(somePath, filename);
string str = File.ReadAllText(path);
str = str.Replace("AS", "");
File.WriteAllText(path, str);
}
Here's a quick example using ReadAllLines() and WriteAllLines():
string[] lines;
string somePath = #"C:\test\";
foreach (string x in a)
{
string path = Path.Combine(somePath, x);
lines = File.ReadAllLines(path);
for (int i = 0; i < lines.Length;i++)
{
lines[i] = lines[i].Replace("AS", "");
string[] values = lines[i].Split(',');
if (values.Length >= 3)
{
string[] parts = values[2].Split('-');
if (parts.Length == 3)
{
values[2] = String.Format("{0}/{1}/{2}", parts[2], parts[1], parts[0]);
lines[i] = String.Join(",", values);
}
}
}
File.WriteAllLines(path, lines);
}
Just loop through all the lines, split the string, try to parse it, then write it in the correct format to the output file.
foreach (string x in a)
{
string somePath = #"C:\test\";
string filename = x;
string path = Path.Combine(somePath, filename);
string str = File.ReadAllText(path);
str = str.Replace("AS", "");
var lines = str.Split('\n');
foreach(var line in lines)
{
var parts = line.Split(',');
if(parts.Length > 2)
{
var d = parts[2];
DateTime dateValue;
if (DateTime.TryParseExact(d, "dd-MM-yyyy", new CultureInfo("en-US"),
DateTimeStyles.None, out dateValue))
{
var dateTxt = dateValue.ToString("yyyy/mm/dd");
...etc...
}
}
}
File.WriteAllText(path, str);
}
Related
Hello I need to find a word in my Richtextbox I need to find the string "ERP Points and ERP Bonus Point"
Here's the contents of a Richboxtext:
https://pastebin.com/vdPQx5E4
Now here's my code:
string resultString = "";
foreach (string line in richTextBox2.Lines)
{
if (line.Contains("ERP Points") || line.Contains("ERP Bonus Point"))
{
resultString = richTextBox2.GetLineFromCharIndex(richTextBox2.Find("ERP", RichTextBoxFinds.MatchCase)).ToString();
var result = Regex.Replace(line, #"\D", "");
string output = Regex.Replace(line, "[^0-9]+", string.Empty);
MessageBox.Show(resultString);
MessageBox.Show(output);
FontArial = 1;
FontSize = Int32.Parse(output);
}
else
{
FontArial = 0;
FontSize = 0;
}
}
and here's my another version which gives me 153 and I don't know where the program gets that:
resultString = richTextBox2.GetLineFromCharIndex(richTextBox2.Find("ERP", RichTextBoxFinds.None)).ToString();
var result = Regex.Replace(line, #"\D", "");
string output = Regex.Replace(resultString, "[^0-9]+", string.Empty);
MessageBox.Show(resultString.ToString());
MessageBox.Show(output);
if (output != "")
{
FontArial = 1;
FontSize = Int32.Parse(output);
}
else
{
FontArial = 0;
FontSize = 0;
}
within my Csv File i have a column which holds a string and a datetime type. i would like to separate these data in two columns, one column which holds the string and one which holds the date but converts the datetime type as a string too.
After doing some research i noticed that i could use the string.split function which will add a comma after the three character which are TIP and then push the date in a new column. however i do not know to code this process
class Program
{
static void Main(string[] args)
{
string currentDirectory = Directory.GetCurrentDirectory();
DirectoryInfo directory = new DirectoryInfo(currentDirectory);
var fileName = Path.Combine(directory.FullName, "Climate 02_08_2016.csv");
var fileContents = ReadFile(fileName);
string[] fileLines = fileContents.Split(new char[] { 'r', 'n' }, StringSplitOptions.RemoveEmptyEntries);
foreach (var line in fileLines)
{
Console.WriteLine(line);
}
}
public static string ReadFile(string fileName)
{
var column5 = new List<string>();
using (var reader = new StreamReader(fileName))
{
while (reader.EndOfStream)
{
var splits = reader.ReadLine().Split(';');
column5.Add(splits[4]);
}
return reader.ReadToEnd();
}
}
}
String.Split splits a string into array of strings based on a delimiter specified. MSDN Reference.
You could use String.Replace method to replace space with a comma.
var result = yourStringVar.Replace(' ', ',')
Here is the full code (slightly simplified).
class Program
{
static void Main(string[] args)
{
var filePath = Path.Combine(Directory.GetCurrentDirectory(), "Climate 02_08_2016.csv");
var fileContents = ReadFile(filePath);
foreach (var line in fileContents)
{
Console.WriteLine(line);
}
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
public static IList<string> ReadFile(string fileName)
{
var results = new List<string>();
var lines = File.ReadAllLines(fileName);
for (var i = 0; i < lines.Length; i++)
{
// Skip the line with column names
if (i == 0)
{
continue;
}
// Replace space with a comma
var replace = lines[i].Replace(' ', ',');
results.Add(replace);
}
return results;
}
}
I get following output:
TUI,01/01/20
Press any key to exit...
Please let me know if this is enough for you to implement your own solution.
So, I know my headline is a bit confusing, I will explain.
My code looks like this:
string filename = "C:\\C#\\maplist.txt"; // please put the text file path.
string filename2 = "C:\\C#\\zemaplist.txt";
string map;
StreamReader sr = new StreamReader(filename);
StreamWriter sw = new StreamWriter(filename2);
List<string> maps = new List<string> { };
while ((map = sr.ReadLine()) != null)
{
maps.Add(map);
}
sr.Close();
for (int i = 0; i < maps.Count; i++)
{
Console.WriteLine(maps[i]);
sw.WriteLine(maps[i]);
}
sw.Close();
and what i need to do is when the code read a new line, in my line there is
"Hey,Hey"
I want to split the , from each other so I can take both of them as other parameters, so that the first Hey will be added to maps and the other hey will be maps2,
How can I do that?
You can use Split() function to Split the given String based on delimiter.
Try This:
while ((map = sr.ReadLine()) != null)
{
maps.Add(map.Split(',')[0].Trim());
maps2.Add(map.Split(',')[1].Trim());
}
Simple Code:
using System.IO;
string filename = "C:\\C#\\maplist.txt"; // please put the text file path.
string filename2 = "C:\\C#\\zemaplist.txt";
string map;
StreamWriter sw = new StreamWriter(filename2);
List<string> maps = new List<string> { };
List<string> maps2 = new List<string> { };
String [] allLines = File.ReadAllLines(filename);
foreach(String line in allLines)
{
maps.Add(line.Split(',')[0].Trim());
maps2.Add(line.Split(',')[1].Trim());
}
for (int i = 0; i < maps.Count; i++)
{
Console.WriteLine(maps[i]);
sw.WriteLine(maps[i]);
}
sw.Close();
Solution 2:
String mapItem1="";
String mapItem2="";
if(maps.Count == maps2.Count)
{
for(int i=0;i<maps.Count;i++)
{
mapItem1=maps[i];
mapItem2=maps2[i];
}
}
while ((map = sr.ReadLine()) != null)
{
string[] split = map.Split(',');
//First Hey would be split[0], second Hey would be split[1]
maps.Add(split[0].Trim());
maps2.Add(split[1].Trim());
}
The Split method should help you out with that.
If you want to trim leading whitespace characters, you can use the .Trim() method on a string.
Use Split().
string heys = "Hey,Hey";
string[] splitArray = heys.Split(',');
Then you have:
splitArray[0] = "Hey";
splitArray[1] = "Hey";
Why even bother reading line by line? Read the entire file, replace the new line chars for a "," (to prevent last and first elements from different lines to be treated as one), and loop through a clean string.
string fileContent = Regex.Replace(File.ReadAllText("test.txt"), #"\r", ",");
List<string> mapList = new List<string>();
foreach (string map in Regex.Split(fileContent.Replace(#"\s+", ""), ","))
{
mapList.Add(map.Trim());
}
I want to read words in a text file of a line separated by commas in c sharp.
For example, I want to read this line:
9/10/2011 10:05,995.4,998.8,995.4,997.5,118000
and get the values: 9/10/2011 10:05, 995.4, 998.8, 995.4, 997.5 and 118000.
Next, I also need to change the format of the date to MMddYYYY, and of the time to HHmmss (e.g. 100500).
I am using this code for reading is there anything wrong
private void button1_Click(object sender, EventArgs e)
{
StreamReader reader1 = File.OpenText(Path1);
string str = reader1.ReadToEnd();
reader1.Close();
reader1.Dispose();
// File.Delete(Path1);
string[] Strarray = str.Split(new char[] { Strings.ChrW(7) });
int abc = Strarray.Length - 1;
int xyz = 0;
bool status = true;
while (xyz <= abc)
{
try
{
status = true;
string[] strarray1 = Strarray[xyz].Split(",".ToCharArray());
string SecName = strarray1[0];
int a2 = 0;
while (status) //If the selected list is empty or the text file has selected name this will execute
{
status = false;
string SecSym = strarray1[1];
int DT = int.Parse(strarray1[2]);
int TM = int.Parse(strarray1[3]);
float O = float.Parse(strarray1[2]);
float H = float.Parse(strarray1[3]);
float L = float.Parse(strarray1[4]);
float C = float.Parse(strarray1[5]);
double OI = double.Parse(Convert.ToString(0));
float V = float.Parse(strarray1[6]);
// string a = string.Concat(SecName, ",",SecSym,",", DT, ",", TM, ",", O, ",", H, ",", L);
//writer.WriteLine(a);
}
}
catch
{ }
}
}
}
.Net comes with a ready CSV parser you can use to get your data. It's a part of VB.net, but you can easily use it in C# by adding a reference to the assembly Microsoft.VisualBasic (it's OK, honesly), and a using statement: using Microsoft.VisualBasic.FileIO;.
The code should be simple to understand:
List<String[]> fileContent = new List<string[]>();
using(FileStream reader = File.OpenRead(#"data.csv")) // mind the encoding - UTF8
using(TextFieldParser parser = new TextFieldParser(reader))
{
parser.TrimWhiteSpace = true; // if you want
parser.Delimiters = new[] { "," };
parser.HasFieldsEnclosedInQuotes = true;
while (!parser.EndOfData)
{
string[] line = parser.ReadFields();
fileContent.Add(line);
}
}
CSV is fairly simple, but it may contain quoted values with commas and newlines, so using Split isn't the best option.
Use the String.Split method to get an array of strings:
string[] ar = line.Split(',')
This should get you started.
using System;
using System.IO;
public class Sample
{
public static void Main() {
using (StreamReader reader = new StreamReader("yourfile.txt")) {
string line = null;
while (null != (line = reader.ReadLine())) {
string[] values = line.Split(',');
DateTime date = DateTime.Parse(values[0];
float[] numbers = new float[values.Length - 1];
for (int i = 1; i < values.Length - 1; i++)
numbers[i - 1] = float.Parse(values[i]);
// do stuff with date and numbers
}
}
}
}
I have also posted a simple CsvReader class which may be helpful for you.
For a quick and simple solution, you can stream through the file and parse each line using String.Split like this:
using (var sr = File.OpenText("myfile.csv"))
{
string line;
while ((line = sr.ReadLine()) != null)
{
var fields = line.Split(',');
var date = DateTime.Parse(fields[0].Trim());
var value1 = fields[0].Trim();
}
}
However, this appraoch if fairly error prone, for a more robust solution check out the CsvReader project, it's excellent for parsing CSV files like this. It will handle field values with commas, trimming spaces before and after fields, and much more.
If you need to parse a date string from a format not recognised by DateTime.Parse, try using DateTime.ParseExact instead.
For 1st part of your task use Split method with , as separator. To convert string datetime from one format to another you need to convert that string to datetime(DateTime.Parse, DateTime.ParseExact) and then convert to final format using DateTime.ToString method.
rows contain your output
StreamReader sStreamReader = new StreamReader("File Path");
string AllData = sStreamReader.ReadToEnd();
string[] rows = AllData.Split(",".ToCharArray());
I am having a problem with reading the files and subfolders. My code reads fine for the given fixed source path, E:\\Folder\\test\\test2.
There are many folders in the test, like test2, test3, test4, etc. I want to extract the data files in the main folder, test.
For example, I want to extract the files in test, so I want to read all the files contained in the test instead of writing my code for test3, test4 and many. And I want to extract and write all the files as same source structure on another drive.
like, if the source structure is like E:\\Folder\\test\\test2 then the destination structure should be like C:\\Folder\\test\\test2
Is there any way to do this?
Here is my code,
private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
{
DateTime dt = dateTimePicker1.Value;
txtSelectedDate.Text = dt.ToString("yyyyMMdd");
selectedDate = txtSelectedDate.Text;
}
private void button2_Click(object sender, EventArgs e)
{
DateTime stdate = Datetimepicker1.value;
while (stdate <= DateTime.Now)
{
txtSelectedDate.Text = stdate.ToString("yyyyMMdd");
selectedDate = txtSelectedDate.Text;
string DayBgSpot = "E:\\Folder\\test\\test2";
string DayBgSpotDestination = "E:\\Folder1";
int DT = int.Parse(txtSelectedDate.Text);
FileReader Reader = new FileReader();
FileReader Reader1 = new FileReader();
Reader.OpenDirectory(DayBgSpot);
Reader.ReadNaster();
string path = DayBgSpotDestination + "\\" + txtSelectedDate.Text + ".txt";
StreamWriter Strwriter = new StreamWriter(path);
try
{
while (Reader.iMaRecordsLeft > 0)
{
string SecName = Reader.sMaSecName;
string Symbol = Reader.sMaSecSymbol;
Symbol = prefix + Symbol;
int abc = 0;
Reader.OpenSecurityByName(Reader.sMaSecName);
if (Reader.iSeRecords > 0)
{
while (Reader.iSeRecordsLeft > 0)
{
Reader.ReadDay();
float O = Reader.dSeo;
float H = Reader.dSeh;
float L = Reader.dSel;
float C = Reader.dSec;
double V = Reader.dSeV;
double OI = Reader.dSrest;
string T = Reader.iSeTime.ToString();
string D = Reader.iSeDate.ToString();
if (int.Parse(D) == DT)
{
string a = string.Concat(SecName, ",", Symbol, ",", D, ",", T, ",", O, ",", H, ",", L, ",", C, ",", V, ",", OI);
if (SecName != "" && V != 0)
{
Strwriter.WriteLine(a);
}
}
}
}
abc++;
Reader.ReadNaster();
}
Reader.CloseDirectory();
Strwriter.Close();
Strwriter.Dispose();
}
catch
{
}
stdate = stdate.AddDays (1); // It will get next date till present
}
}
Something like
System.IO.DirectoryInfo baseFolder = new DirectoryInfo(#"c:\Folder\test\");
string destinationPath = #"e:\Folder\test\";
System.IO.DirectoryInfo[] subDirs = baseFolder.GetDirectories();
foreach (System.IO.DirectoryInfo dirInfo in subDirs)
{
string subFolder = dirInfo.Name;
System.IO.FileInfo[] fileInfos = dirInfo.GetFiles("*.txt");
foreach (System.IO.FileInfo fileInfo in fileInfos)
{
// Do something with the files
string writePath = destinationPath + subFolder + #"\" + fileInfo.Name;
// Write
}
}
If you are using .NET 4.0 this is one line:
var filepaths = Directory.GetFiles(path: #"C:\", searchPattern: "*pattern*", searchOption: SearchOption.AllDirectories);
Clearly, the root path and search pattern are not in line with the proposed sample, but my intention should clear.
I hope this helps