Editing/Saving a row in a CSV file - c#

After following this topic I am able to create
the new row but my question is how do
I save or write the new line to the file?
I tried 'StreamWriter' but it only writes the newly
created line.
Any suggestions please?
Here is my code so far:
string path = #"C:/CSV.txt";
string[] lines = File.ReadAllLines(path);
var splitlines = lines.Select(l => l.Split(','));
foreach (var line in splitlines)
{
if(line[1].Contains("34"))
{
line[1] = "100";
var newline = string.Join(",", line);
StreamWriter sr = new StreamWriter(path);
sr.WriteLine(newline);
sr.Close();
}
}

Here is your solution using StreamReader class:
String path = #"C:\CSV.txt";
List<String> lines = new List<String>();
if (File.Exists(path));
{
using (StreamReader reader = new StreamReader(path))
{
String line;
while ((line = reader.ReadLine()) != null)
{
if (line.Contains(","))
{
String[] split = line.Split(',');
if (split[1].Contains("34"))
{
split[1] = "100";
line = String.Join(",", split);
}
}
lines.Add(line);
}
}
using (StreamWriter writer = new StreamWriter(path, false))
{
foreach (String line in lines)
writer.WriteLine(line);
}
}
If you want to overwrite the file, use this StreamWriter constructor with append = false.

Maybe somthing like this, you probably will need to clean it up and add some error handling, but it does the job
string path = #"C:\\CSV.txt";
string[] lines = File.ReadAllLines(path);
for (int i = 0; i < lines.Length; i++)
{
string line = lines[i];
if (line.Contains(","))
{
var split = line.Split(',');
if (split[1].Contains("34"))
{
split[1] = "100";
line = string.Join(",", split);
}
}
}
File.WriteAllLines(#"C:\\CSV.txt", lines);

string str;
string PID;
string PN;
string UP;
string DIS;
string STK;
string CSVFilePathName = #"C:\admin.csv";
string[] Lines = File.ReadAllLines(CSVFilePathName);
File.Delete(CSVFilePathName);
StreamWriter sw = new StreamWriter(CSVFilePathName", true);
PID = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[0].Controls[0])).Text;
PN = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[1].Controls[0])).Text;
UP = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[2].Controls[0])).Text;
DIS = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[3].Controls[0])).Text;
STK = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[4].Controls[0])).Text;
foreach (string li in Lines)
{
string[] Fields = li.Split(',');
if(PID==Fields[0])
{
str = PID + "," + PN + "," + UP + "," + DIS + "," + STK;
}
else
{
str = Fields[0] + "," + Fields[1] + "," + Fields[2] + "," + Fields[3] + "," + Fields[4];
}
sw.WriteLine(str);
}
sw.Flush();
sw.Close();

Related

C# Save XLS to CSV: Index was outside the bounds of the array

System.IndexOutOfRangeException: Index was outside the bounds of the array.
How to solve this error ?
Can anyone know this ?
Below my coding... when execute it produce the error that
System.IndexOutOfRangeException Index was outside the bounds of the array
, only if tried to process this csv file :
Instead I don't have error if tried to process this csv file :
Excel.IExcelDataReader excelReader = Excel.ExcelReaderFactory.CreateBinaryReader(stream);
DataSet result = excelReader.AsDataSet();
excelReader.Close();
result.Tables[0].TableName.ToString();
string csvData = "";
int row_no = 0;
int ind = 0;
while (row_no < result.Tables[ind].Rows.Count)
{
for (int i = 0; i < result.Tables[ind].Columns.Count; i++)
{
csvData += result.Tables[ind].Rows[row_no][i].ToString() + "|";
}
row_no++;
csvData += "\n";
}
keys = GetUniqueKey(12).ToUpper();
output = System.Web.HttpContext.Current.Server.MapPath("/public/" + keys.ToString() + ".csv");
StreamWriter csv = new StreamWriter(#output, false);
csv.Write(csvData);
csv.Close();
csv.Dispose();
string toCheck;
using (var fs = new FileStream(output, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (var sr = new StreamReader(fs, Encoding.Default))
{
toCheck = sr.ReadToEnd();
if (toCheck.Contains("ColumnAAA") == false)
{
////Start add new column
int posNewColumn = 2;
string[] CSVDump = File.ReadAllLines(output);
List<List<string>> CSV = CSVDump.Select(x => x.Split('|').ToList()).ToList();
for (int i = 0; i < CSV.Count; i++)
{
if (CSV[i].Count > posNewColumn)
{
CSV[i].Insert(posNewColumn, i == 0 ? "ColumnAAA" : "ColumnAAA");
}
else
{
CSV[i].Add(i == 0 ? "ColumnAAA" : "ColumnAAA");
}
}
File.WriteAllLines(output, CSV.Select(x => string.Join("|", x)));
sr.Close();
////End add new column
}
}
Edit #01
The problem is in this line of code-behind.
The code print correctly the number of rows, but I have error when try print and Split the number of columns :
lines = File.ReadAllLines(System.Web.HttpContext.Current.Server.MapPath("/public/" + keys.ToString() + ".csv"));
rows = lines.Count();
columns = lines[23].Split('|').Count();
Response.Write("Number of rows/columns = " + rows.ToString() + "/" + columns.ToString());
Response.End();
Try this :
lines = File.ReadAllLines(System.Web.HttpContext.Current.Server.MapPath("/public/" + keys.ToString() + ".csv"));
rows = lines.Count();
int i = 0;
foreach (string line in lines)
{
string[] parts = line.Split('|');
foreach (string part in parts)
{
columns = parts.Count();
}
i++;
}
Response.Write("Number of rows/columns = " + rows.ToString() + "/" + columns.ToString());
Response.End();

convert vertically listed strings of a text file to horizontal format

I have a text file "Test 2.txt" with the below format:
string1
string2
string3
string4
string5
string6
string7
string8
string9
...and so on...
I would like to convert it to text file "Test.txt" with below format:
string1,string2,string3
string4,string5,string6
string7,string8,string9
...and so on...
My code at the moment is below:
string line;
string DatabaseFullPath = #"C:\Test2.xsr";
using (var file = new StreamReader(DatabaseFullPath, Encoding.UTF8))
{
int count = File.ReadLines(DatabaseFullPath).Count();
while ((line = file.ReadLine()) != null)
{
count++;
if (count % 3 == 0)
{
using (StreamWriter writetext = new StreamWriter(#"D:\Test.txt"))
{
writetext.WriteLine(line + '\n');
}
}
else
{
using (StreamWriter writetext = new StreamWriter(#"D:\Test.txt"))
{
writetext.Write(line + ',');
}
}
}
}
It seems that the StreamWriter is just overwriting each string "line" with another string "line" but I am not sure about it.
string DatabaseFullPath = #"C:\Test2.xsr";
using (var file = new StreamReader(DatabaseFullPath, Encoding.UTF8)) {
using (StreamWriter writetext = new StreamWriter(#"D:\Test.txt")) {
int count = 0;
string line;
while ((line = file.ReadLine()) != null) {
if (++count % 3 == 0)
writetext.WriteLine(line);
else
writetext.Write(line + ',');
}
}
}

Convert .XYZ to .csv using c#

Hi i am using this method to replace " " to "," but is failing when i try to use it on data that have 32 millions lines. Is anyone knows how to modify it to make it running?
List<String> lines = new List<String>();
//loop through each line of file and replace " " sight to ","
using (StreamReader sr = new StreamReader(inputfile))
{
int id = 1;
int i = File.ReadAllLines(inputfile).Count();
while (sr.Peek() >= 0)
{
//Out of memory issuee
string fileLine = sr.ReadLine();
//do something with line
string ttt = fileLine.Replace(" ", ", ");
//Debug.WriteLine(ttt);
lines.Add(ttt);
//lines.Add(id++, 'ID');
}
using (StreamWriter writer = new StreamWriter(outputfile, false))
{
foreach (String line in lines)
{
writer.WriteLine(line+","+id);
id++;
}
}
}
//change extension to .csv
FileInfo f = new FileInfo(outputfile);
f.MoveTo(Path.ChangeExtension(outputfile, ".csv"));
I general i am trying to convert big .XYZ file to .csv format and add incremental field at the end. I am using c# for first time in my life to be honest :) Can you help me?
See my comment above - you could modify your reading / writing as follows :
using (StreamReader sr = new StreamReader(inputfile))
{
using (StreamWriter writer = new StreamWriter(outputfile, false))
{
int id = 1;
while (sr.Peek() >= 0)
{
string fileLine = sr.ReadLine();
//do something with line
string ttt = fileLine.Replace(" ", ", ");
writer.WriteLine(ttt + "," + id);
id++;
}
}
}

Reading, Manipulating, and Writing text files C#

I need to convert any flat delimited file into a pipe delimited format. I wrote this console app as a POC but the second file it tries to write will include the all of the text from the first file. Any suggestions?
string sourceDir = #"c:\temp\";
string targetDir = #"c:\dest\";
List<string> listLines = new List<string>();
string[] files = Directory.GetFiles(sourceDir);
foreach(string file in files)
{
using (StreamReader sr = new StreamReader(sourceDir + Path.GetFileName(file)))
{
do
{
listLines.Add(sr.ReadLine());
} while (!sr.EndOfStream);
for (int i = 0; i < listLines.Count; i++)
{
listLines[i] = listLines[i].Replace(',', '|');
listLines[i] = listLines[i].Replace('\t', '|');
}
}
using (StreamWriter sw = new StreamWriter(targetDir + Path.GetFileName(file)))
{
foreach (string line in listLines)
{
sw.WriteLine(line);
}
}
}
You need to either move the instantiation of listLines into the foreach, or re-initialize the list at the end of the loop.
string sourceDir = #"c:\temp\";
string targetDir = #"c:\dest\";
string[] files = Directory.GetFiles(sourceDir);
foreach(string file in files)
{
List<string> listLines = new List<string>();
using (StreamReader sr = new StreamReader(sourceDir + Path.GetFileName(file)))
{
do
{
listLines.Add(sr.ReadLine());
} while (!sr.EndOfStream);
for (int i = 0; i < listLines.Count; i++)
{
listLines[i] = listLines[i].Replace(',', '|');
listLines[i] = listLines[i].Replace('\t', '|');
}
}
using (StreamWriter sw = new StreamWriter(targetDir + Path.GetFileName(file)))
{
foreach (string line in listLines)
{
sw.WriteLine(line);
}
}
}
You're adding lines to listLines and never clearing the list after the foreach iteration.
by #Jonathan Carroll
Beside that, you can improve your code to this:
string sourceDir = #"c:\temp\";
string targetDir = #"c:\dest\";
List<string> listLines = new List<string>();
string[] files = Directory.GetFiles(sourceDir);
foreach (string file in files)
{
using (StreamReader sr = new StreamReader(sourceDir + Path.GetFileName(file)))
using (StreamWriter sw = new StreamWriter(targetDir + Path.GetFileName(file)))
{
do
{
var line = sr.ReadLine();
line = line.Replace(',', '|').Replace('\t', '|');
sw.WriteLine(line);
} while (!sr.EndOfStream);
}
}
I'd argue that the other answers are considerably clearer, but just thought I'd throw in a short alternative solution using LINQ and Regex:
foreach (var file in Directory.GetFiles(sourceDir).Select(x => Path.GetFileName(x)))
File.WriteAllText(targetDir + file, new Regex("[,\t]").Replace(File.ReadAllText(sourceDir + file), "|"));
The LINQ select query is used to transform the full paths into file names - this collection of file names is then iterated over.
Regex is used to match all ',' and '\t' characters that are read from the source file and replace them with the '|' character. This resulting string is then written to the target file.

How to separate CSV delimited data and store the values accordingly?

I've data in CSV in the pattern
A,B,C,D,E,F,G
C,F,G,L,K,O,F
a,b,c,d,e,f,g
f,t,s,n,e,K,c
B,F,d,e,t,m,A
I want these data to store in the form of:
A,B,C,D
B,C,D,E
C,D,E,F
D,E,F,G
.
.
.
While I'm trying to do in the below way, I missing one pattern in middle. for ex: C,D,E,F
Here is my code:
static void Main(string[] args)
{
FileStream fs = new FileStream("studentSheet.csv", FileMode.Open);
StreamReader reader = new StreamReader(fs);
List<string> subline = new List<string>();
string line = "";
while ((line = reader.ReadLine()) != null)
{
string[] splitstring = line.Split(';');
string ft = null;
int i =0;
while(i <( splitstring.Length - 3)+1)
{
ft = splitstring[i] + "," + splitstring[i+1]
+ "," + splitstring[i+2] +","+ splitstring[i+3];
subline.Add(ft);
i = i + 1;
}
}
foreach(string s in subline)
Console.WriteLine(s);
Console.ReadLine();
}
Assuming you're ok with reading it all into one big list called input, and you don't need it to be amazingly fast, you can just do:
List<string> output = Enumerable.Range(0, input.Length - 4)
.Select(i => String.Join(",", input.Skip(i).Take(4)))
.ToList();

Categories