CSV update/modification - c#

Trying to override a single record of the following CSV:
PRODUCT,RECORD,ACCOUNT
100,200,300
using this code:
public static void UpdateCSV(string filePath, string stringToReplace, string updatedString)
{
string path = filePath;
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(stringToReplace))
{
split[1] = updatedString;
line = string.Join(",", split);
}
}
lines.Add(line);
}
}
using (StreamWriter writer = new StreamWriter(path, false))
{
foreach (string line in lines)
writer.WriteLine(line);
}
}
}
But invoking the following does not make a difference ('PRODUCT' does not change to 'MYPRODUCT'):
UpdateCSV(#"C:\Test.csv", "PRODUCT", "MYPRODUCT");
What's wrong here?

Related

Add data to CSV if string is not found

I have an application that updates data within a CSV. What I am trying to add is, if the "name" is not in the CSV, then add it. I have tried changing the while to an if/then, but that gave me no results, just a blank line within the CSV.
Code:
using (StreamReader reader = new StreamReader(path))
{
String line;
while ((line = reader.ReadLine()) != null)
{
if (line.Split(',')[0].Equals("newName"))
{
String[] split = line.Split(',');
split[1] = tPoints.ToString();
line = String.Join(",", split);
}
lines.Add(line);
}
}
using (StreamWriter writer = new StreamWriter(path))
{
foreach (String line in lines)
writer.WriteLine(line);
}
Current CSV Data:
name,734937
If item is NOT found, I am trying have it add a new row. So expected result would be something similar to below:
name,734937
newName,0
You can try something like this:
bool termFound = false;
string searchTerm = "newName";
var lines = new List<string>();
using (StreamReader reader = new StreamReader("input.csv"))
{
string line;
while ((line = reader.ReadLine()) != null)
{
lines.Add(line);
if (line.Split(',')[0].Equals(searchTerm))
termFound = true;
}
}
using (StreamWriter writer = new StreamWriter("output.csv"))
{
foreach (string line in lines)
writer.WriteLine(line);
if(termFound == false)
writer.WriteLine($"{searchTerm},0");
}

Comparing rows in a csv file

I am currently using the below code to compare two csv files with each other. This code gives an output with all the rows that are not the same. But when a row is missing everything after that row is not the same. How can I fix this? Thanks in advance.
List<string> lines = new List<string>();
List<string> lines2 = new List<string>();
try
{
StreamReader reader = new StreamReader(System.IO.File.OpenRead(file1));
StreamReader read = new StreamReader(System.IO.File.OpenRead(file2));
List<string> differences = new List<string>();
string line;
string line2;
int i = 0;
while ((line = reader.ReadLine()) != null && (line2 = read.ReadLine()) != null)
{
string[] split = line.Split(Convert.ToChar("\t"));
string[] split2 = line2.Split(Convert.ToChar("\t"));
if (split[i] != split2[i])
{
differences.Add("this row is not the same:, " + line);
}
else
{
}
i++;
}
System.IO.File.WriteAllLines(differencesFile, differences);
reader.Dispose();
read.Dispose();
}
catch
{
}
After help from a friend I made it work with this code:
List<string> file1 = new List<string>();
List<string> output = new List<string>();
string differencesFile = path;
File.WriteAllText(differencesFile, "");
try
{
StreamReader readFile1 = new StreamReader(System.IO.File.OpenRead(pathfile1));
string lineFile1;
while ((lineFile1 = readFile1.ReadLine()) != null)
{
bool match = false;
string[] colums = lineFile1.Split('\t');
StreamReader readFile2 = new StreamReader(System.IO.File.OpenRead(pathfile2));
string line2;
while ((line2 = readFile2.ReadLine()) != null)
{
string[] columsFile2 = line2.Split('\t');
if (colums[0] == columsFile2[0])
{
match = true;
}
}
if (!match)
{
output.Add(colums[0] + "; doesnt exist in pathfile2");
}
}
System.IO.File.WriteAllLines(differencesFile, output);
}
catch { }

Reading and changing a file

I'm reading a file using C# and class TextReader
TextReader reader = new StreamReader(stream);
string line;
while ((line = reader.ReadLine()) != null)
{
if (someCondition)
{
// I want to change "line" and save it into the file I'm reading from
}
}
In a code there is a question: how do I save a changed line to a file I'm reading from and continue reading?
Fast and dirty solution would be:
TextReader reader = new StreamReader(stream);
string line;
StringBuilder sb = new StringBuilder();
while ((line = reader.ReadLine()) != null)
{
if (someCondition)
{
//Change variable line as you wish.
}
sb.Append(line);
}
using (StreamWriter sw = new StreamWriter("filePath"))
{
sw.Write(sb.ToString());
}
or
TextReader reader = new StreamReader(stream);
string line;
String newLines[];
int index = 0;
while ((line = reader.ReadLine()) != null)
{
if (someCondition)
{
//Change variable line as you wish.
}
newLines[index] = line;
index++;
}
using (StreamWriter sw = new StreamWriter("filePath"))
{
foreach (string l in newLines)
{
sw.WriteLine(l);
}
}
If memory is too important you can try this too:
TextReader reader = new StreamReader(stream);
string line;
while ((line = reader.ReadLine()) != null)
{
if (someCondition)
{
//Change variable line as you wish.
}
using (StreamWriter sw = new StreamWriter("filePath"))
{
sw.WriteLine(line);
}
}
The easiest thing is to write a new file, then when finished, replace the old file with the new file. This way you only do writes in one file.
If you try to read/write in the same file, you will run into problems when the content you want to insert is not the exact same size as the content it is replacing.
There is nothing magic about text files. They are just a stream of bytes representing characters in a text encoding. There are no line concept in the file, just separators in the form of newline characters.
If the file is not too large, you should simply rewrite the whole file:
var lines = File.ReadAllLines(path)
.Where(l => someCondition);
File.WriteAllLines(path, lines);
A very simple solution
void Main()
{
var lines = File.ReadAllLines("D:\\temp\\file.txt");
for(int x = 0; x < lines.Length; x++)
{
// Of course this is an example of the condtion
// you should implement your checks
if(lines[x].Contains("CONDITION"))
{
lines[x] = lines[x].Replace("CONDITION", "CONDITION2");
}
}
File.WriteAllLines("D:\\temp\\file.txt", lines);
}
The drawback is the memory usage caused by the in memory lines, but, if we stay around 50MB, it should be handled effortlessly by modern PC.

Open a resource file with StreamReader?

This doesnt work:
string fileContent = Resource.text;
StreamReader read = File.OpenText(fileContent);
string line;
char[] splitChar = "|".ToCharArray();
while ((line = read.ReadLine()) != null)
{
string[] split = line.Split(splitChar);
string name = split[0];
string lastname = split[1];
}
read.Dispose();
How do you open a resource file to get its contents?
Try like this:
string fileContent = Resource.text;
using (var reader = new StringReader(fileContent))
{
string line;
while ((line = reader.ReadLine()) != null)
{
string[] split = line.Split('|');
string name = split[0];
string lastname = split[1];
}
}
I think the variable fileContent already has all the contents you need.
to read resources, you need a special Stream named "ResourceReader", you can use it like this :
string fileContent = "<your resource file>";
using (ResourceReader reader = new ResourceReader(fileContent))
{
foreach (IDictionaryEnumerator dict in reader)
{
string key = dict.Key as string;
object val = dict.Value;
}
}

Open a file and replace strings in C#

I'm trying to figure out the best way to open an existing file and replace all strings that match a declared string with a new string, save it then close.
Suggestions ?
Can be done in one line:
File.WriteAllText("Path", Regex.Replace(File.ReadAllText("Path"), "[Pattern]", "Replacement"));
If you're reading large files in, and your string for replacement may not appear broken across multiple lines, I'd suggest something like the following...
private static void ReplaceTextInFile(string originalFile, string outputFile, string searchTerm, string replaceTerm)
{
string tempLineValue;
using (FileStream inputStream = File.OpenRead(originalFile) )
{
using (StreamReader inputReader = new StreamReader(inputStream))
{
using (StreamWriter outputWriter = File.AppendText(outputFile))
{
while(null != (tempLineValue = inputReader.ReadLine()))
{
outputWriter.WriteLine(tempLineValue.Replace(searchTerm,replaceTerm));
}
}
}
}
}
Then you'd have to remove the original file, and rename the new one to the original name, but that's trivial - as is adding some basic error checking into the method.
Of course, if your replacement text could be across two or more lines, you'd have to do a little more work, but I'll leave that to you to figure out. :)
using System;
using System.IO;
using System.Text.RegularExpressions;
public static void ReplaceInFile(
string filePath, string searchText, string replaceText )
{
var content = string.Empty;
using (StreamReader reader = new StreamReader( filePath ))
{
content = reader.ReadToEnd();
reader.Close();
}
content = Regex.Replace( content, searchText, replaceText );
using (StreamWriter writer = new StreamWriter( filePath ))
{
writer.Write( content );
writer.Close();
}
}
Slight improvement on the accepted answer that doesn't require Regex, and which meets the requirements of the question:
File.WriteAllText("Path", File.ReadAllText("Path").Replace("SearchString", "Replacement"));
public partial class ReadAndChange : System.Web.UI.Page
{
ArrayList FolderList = new ArrayList();
ArrayList FolderListSearch = new ArrayList();
ArrayList FileList = new ArrayList();
protected void Page_Load(object sender, EventArgs e)
{
AllFolderList("D:\\BinodBackup\\Nilesh\\14.5.2013\\Source");
foreach (string Path in FolderList)
{
AllFileList(Path);
}
foreach (string Path in FileList)
{
ReplaceFile(Path, Path.Replace("Source", "EditedCode"));
}
//string SourcePath = "D:\\BinodBackup\\Nilesh\\14.5.2013\\Onesource\\Onesource\\UserManagement\\UserControls\\AddUserDetails.ascx.cs";
//string ReplacePath = "D:\\AddUserDetails.ascx.cs";
//ReplaceFile(SourcePath, ReplacePath);
}
private static void ReplaceFile(string SourcePath, string ReplacePath)
{
int counter = 1;
string line;
// Read the file and display it line by line.
System.IO.StreamReader file = new System.IO.StreamReader(SourcePath);
while ((line = file.ReadLine()) != null)
{
if (!(line.Contains("//")))
{
if (line.Contains(".LogException("))
{
//Console.WriteLine(counter.ToString() + ": " + line);
string[] arr = line.Split(',');
string stringToReplace = arr[0].Replace("LogException", "Publish") + " , " + arr[2].Trim() + " , " + arr[3].Replace(");", "").Trim() + " , " + arr[1].Trim() + ");";
//File.WriteAllText(currentPath, Regex.Replace(File.ReadAllText(currentPath), line, line + " Added"));
File.WriteAllText(ReplacePath, File.ReadAllText(ReplacePath).Replace(line, stringToReplace));
//ReplaceInFile(currentPath, line, stringToReplace);
}
}
counter++;
}
file.Close();
}
private void AllFileList(string FolderPath)
{
DirectoryInfo dir = new DirectoryInfo(FolderPath);
DirectoryInfo[] subdir = dir.GetDirectories();
if (subdir.Length > 0)
{
foreach (DirectoryInfo dr in subdir)
{
FileInfo[] files1 = dr.GetFiles();
foreach (FileInfo file in files1)
{
if(file.Name.EndsWith(".cs"))
CheckAndAdd((file.DirectoryName + "\\" + file.Name), FileList);
}
}
}
}
private void AllFolderList(string FolderPath)
{
string CurFolderPatgh = FolderPath;
Again:
AddToArrayList(CurFolderPatgh);
DirectoryInfo dir = new DirectoryInfo(CurFolderPatgh);
DirectoryInfo[] subdir = dir.GetDirectories();
if (subdir.Length > 0)
{
foreach (DirectoryInfo dr in subdir)
{
AddToArrayList(((System.IO.FileSystemInfo)(dir)).FullName + "\\" + dr.Name);
}
}
if (FolderListSearch.Count > 0)
{
foreach (string dr in FolderListSearch)
{
CurFolderPatgh = dr;
FolderListSearch.Remove(dr);
goto Again;
}
}
}
private void AddToArrayList(string FolderPath)
{
if (!(FolderList.Contains(FolderPath)))
{
CheckAndAdd(FolderPath, FolderList);
CheckAndAdd(FolderPath, FolderListSearch);
}
}
private void CheckAndAdd(string FolderPath,ArrayList ar)
{
if (!(ar.Contains(FolderPath)))
{
ar.Add(FolderPath);
}
}
public static void ReplaceInFile(
string filePath, string searchText, string replaceText)
{
var content = string.Empty;
using (StreamReader reader = new StreamReader(filePath))
{
content = reader.ReadToEnd();
reader.Close();
}
content = content.Replace(searchText, replaceText);
using (StreamWriter writer = new StreamWriter(filePath))
{
writer.Write(content);
writer.Close();
}
}
}
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
namespace DevExpressFileEditing
{
class Program
{
static List<FileInfo> _files;
private static Dictionary<string, string> _replaceList;
static void Main()
{
_files = new List<FileInfo>();
_replaceList = new Dictionary<string, string>();
Console.WriteLine("Dark directory searching");
SearchFilesInDirectories(new DirectoryInfo(#"C:\Sourcebank\Dark"));
Console.WriteLine("Light directory searching");
SearchFilesInDirectories(new DirectoryInfo(#"C:\Sourcebank\Light"));
Console.WriteLine("{0} files found", _files.Count.ToString(CultureInfo.InvariantCulture));
Console.WriteLine("Replace dictinary creating");
CreateReplaceList();
Console.WriteLine("{0} item added", _replaceList.Count.ToString(CultureInfo.InvariantCulture));
Console.Write("Replacement doing");
for (int i = 0; i < _files.Count; i++)
{
var fileInfo = _files[i];
Console.CursorLeft = 0;
Console.Write("{0} of {1}", i.ToString(CultureInfo.InvariantCulture), _files.Count.ToString(CultureInfo.InvariantCulture));
ReplaceInFile(fileInfo.FullName);
}
Console.CursorLeft = 0;
Console.Write("Replacement done");
}
private static void SearchFilesInDirectories(DirectoryInfo dir)
{
if (!dir.Exists) return;
foreach (DirectoryInfo subDirInfo in dir.GetDirectories())
SearchFilesInDirectories(subDirInfo);
foreach (var fileInfo in dir.GetFiles())
_files.Add(fileInfo);
}
private static void CreateReplaceList()
{
_replaceList.Add("Color=\"#FFF78A09\"", "Color=\"{DynamicResource AccentColor}\"");
_replaceList.Add("Color=\"{StaticResource ColorHot}\"", "Color=\"{DynamicResource AccentColor}\"");
_replaceList.Add("Color=\"#FFCC0000\"", "Color=\"{DynamicResource AccentColor}\"");
_replaceList.Add("To=\"#FFCC0000\"", "To=\"{DynamicResource AccentColor}\"");
_replaceList.Add("To=\"#FFF78A09\"", "To=\"{DynamicResource AccentColor}\"");
_replaceList.Add("Background=\"#FFF78A09\"", "Background=\"{DynamicResource Accent}\"");
_replaceList.Add("Foreground=\"#FFF78A09\"", "Foreground=\"{DynamicResource Accent}\"");
_replaceList.Add("BorderBrush=\"#FFF78A09\"", "BorderBrush=\"{DynamicResource Accent}\"");
_replaceList.Add("Value=\"#FFF78A09\"", "Value=\"{DynamicResource Accent}\"");
_replaceList.Add("Fill=\"#FFF78A09\"", "Fill=\"{DynamicResource Accent}\"");
}
public static void ReplaceInFile(string filePath)
{
string content;
using (var reader = new StreamReader(filePath))
{
content = reader.ReadToEnd();
reader.Close();
}
content = _replaceList.Aggregate(content, (current, item) => current.Replace(item.Key, item.Value));
using (var writer = new StreamWriter(filePath))
{
writer.Write(content);
writer.Close();
}
}
}
}

Categories

Resources