Open a file and replace strings in C# - 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();
}
}
}
}

Related

CSV update/modification

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?

StreamWriter: Starting and ending on a specific line number

I would like to ask some tips and help on a reading/writing part of my C#.
Situation:
I have to read a CSV file; - OK
If the CSV file name starts with "Load_", I want to write on another CSV the data from line 2 to the last one;
If the CSV file name starts with "RO_", I want to write on 2 different CSVs, 1 with the line 1 to 4 and the other 4 to the last one;
What I have so far is:
public static void ProcessFile(string[] ProcessFile)
{
// Keeps track of your current position within a record
int wCurrLine = 0;
// Number of rows in the file that constitute a record
const int LINES_PER_ROW = 1;
int ctr = 0;
foreach (string filename in ProcessFile)
{
var sbText = new System.Text.StringBuilder(100000);
int stop_line = 0;
int start_line = 0;
// Used for the output name of the file
var dir = Path.GetDirectoryName(filename);
var fileName = Path.GetFileNameWithoutExtension(filename);
var ext = Path.GetExtension(filename);
var folderbefore = Path.GetFullPath(Path.Combine(dir, #"..\"));
var lineCount = File.ReadAllLines(#filename).Length;
string outputname = folderbefore + "output\\" + fileName;
using (StreamReader Reader = new StreamReader(#filename))
{
if (filename.Contains("RO_"))
{
start_line = 1;
stop_line = 5;
}
else
{
start_line = 2;
stop_line = lineCount;
}
ctr = 0;
while (!Reader.EndOfStream && ctr < stop_line)
{
// Add the text
sbText.Append(Reader.ReadLine());
// Increment our current record row counter
wCurrLine++;
// If we have read all of the rows for this record
if (wCurrLine == LINES_PER_ROW)
{
// Add a line to our buffer
sbText.AppendLine();
// And reset our record row count
wCurrLine = 0;
}
ctr++;
} // end of the while
}
int total_lenght = sbText.Length
// When all of the data has been loaded, write it to the text box in one fell swoop
using (StreamWriter Writer = new StreamWriter(dir + "\\" + "output\\" + fileName + "_out" + ext))
{
Writer.Write.(sbText.);
}
} // end of the foreach
} // end of ProcessFile
I was thinking about using the IF/ELSE: "using (StreamWriter Writer = new StreamWriter(dir + "\" + "output\" + fileName + "_out" + ext))" part. However, I am not sure how to pass, to StreamWriter, to only write from/to a specific line number.
Any Help is welcome! If I am missing some information, please, let me know (I am pretty new on stackoverflow).
Thank you.
Code is way too complicated
using System.Collections.ObjectModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ConsoleApplication57
{
class Program
{
static void Main(string[] args)
{
}
public static void ProcessFile(string[] ProcessFile)
{
foreach (string filename in ProcessFile)
{
// Used for the output name of the file
var dir = Path.GetDirectoryName(filename);
var fileName = Path.GetFileNameWithoutExtension(filename);
var ext = Path.GetExtension(filename);
var folderbefore = Path.GetFullPath(Path.Combine(dir, #"..\"));
var lineCount = File.ReadAllLines(#filename).Length;
string outputname = folderbefore + "output\\" + fileName;
using (StreamWriter Writer = new StreamWriter(dir + "\\" + "output\\" + fileName + "_out" + ext))
{
int rowCount = 0;
using (StreamReader Reader = new StreamReader(#filename))
{
rowCount++;
string inputLine = "";
while ((inputLine = Reader.ReadLine()) != null)
{
if (filename.Contains("RO_"))
{
if (rowCount <= 4)
{
Writer.WriteLine(inputLine);
}
if (rowCount == 4) break;
}
else
{
if (rowCount >= 2)
{
Writer.WriteLine(inputLine);
}
}
} // end of the while
Writer.Flush();
}
}
} // end of the foreach
} // end of ProcessFile
}
}
You can use LINQ to Take and Skip lines.
public abstract class CsvProcessor
{
private readonly IEnumerable<string> processFiles;
public CsvProcessor(IEnumerable<string> processFiles)
{
this.processFiles = processFiles;
}
protected virtual IEnumerable<string> GetAllLinesFromFile(string fileName)
{
using(var stream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))
using(var reader = new StreamReader(stream))
{
var line = String.Empty;
while((line = reader.ReadLine()) != null)
{
yield return line;
}
}
}
protected virtual void ProcessFiles()
{
var sb1 = new StringBuilder();
var sb2 = new StringBuilder();
foreach(var file in this.processFiles)
{
var fileName = Path.GetFileNameWithoutExtension(file);
var lines = GetAllLinesFromFile(file);
if(fileName.StartsWith("RO_", StringComparison.InvariantCultureIgnoreCase))
{
sb1.AppendLine(lines.Take(4)); //take only the first four lines
sb2.AppendLine(lines.Skip(4).TakeWhile(s => !String.IsNullOrEmpty(s))); //skip the first four lines, take everything else
}
else if(fileName.StartsWith("Load_", StringComparison.InvariantCultureIgnoreCase)
{
sb2.AppendLine(lines.Skip(1).TakeWhile(s => !String.IsNullOrEmpty(s)));
}
}
// now write your StringBuilder objects to file...
}
protected virtual void WriteFile(StringBuilder sb1, StringBuilder sb2)
{
// ... etc..
}
}

C# System.IO.IOException

I have following code:
using System;
using System.Collections.Generic;
using System.IO;
using VirusTotalNET;
using VirusTotalNET.Objects;
using System.Linq;
using System.Security.Permissions;
namespace VirusTotalNETClient
{
class Program
{
private const string ScanUrl = "http://www.google.com/";
static void Main(string[] args)
{
VirusTotal virusTotal = new VirusTotal("5d8684f50946c2bdeaf5c4fd966f61f3661de808e9d7324b99788d6f4fb7ad57");
//Use HTTPS instead of HTTP
virusTotal.UseTLS = true;
//creating folder for programs reliqies and output log
string folderName = "C:\\OnlineScanner";
System.IO.Directory.CreateDirectory(folderName);
//get list of files to analyse
var paths = Traverse("C:\test");
File.WriteAllLines("C:\\OnlineScanner\\test.txt", paths);
foreach (string line in File.ReadLines("C:\\test.txt"))
{
//Define what file you want to analyse
FileInfo fileInfo = new FileInfo(line);
//Check if the file has been scanned before.
FileReport fileReport = virusTotal.GetFileReport(fileInfo);
bool hasFileBeenScannedBefore = fileReport.ResponseCode == ReportResponseCode.Present;
//If the file has been scanned before, the results are embedded inside the report.
if (hasFileBeenScannedBefore)
{
int detekce = fileReport.Positives;
if (detekce >= 1)
{
using (var writer = new StreamWriter("C:\\OnlineScanner\\OnlineScannerLog.txt"))
{
writer.WriteLine(line);
writer.WriteLine("URL to test: " + fileReport.Permalink);
writer.WriteLine("Detect ratio: " + fileReport.Positives + "/54");
writer.WriteLine("Message: " + fileReport.VerboseMsg);
writer.WriteLine();
writer.WriteLine();
}
}
System.Threading.Thread.Sleep(16000);
}
else
{
ScanResult fileResult = virusTotal.ScanFile(fileInfo);
int detekce = fileReport.Positives;
if (detekce >= 1)
{
using (var writer = new StreamWriter("C:\\OnlineScanner\\OnlineScannerLog.txt"))
{
writer.WriteLine(line);
writer.WriteLine("URL to test: " + fileReport.Permalink);
writer.WriteLine("Detect ratio: " + fileReport.Positives + "/54");
writer.WriteLine("Message: " + fileReport.VerboseMsg);
writer.WriteLine();
writer.WriteLine();
}
}
System.Threading.Thread.Sleep(16000);
}
}
}
private static IEnumerable<string> Traverse(string rootDirectory)
{
IEnumerable<string> files = Enumerable.Empty<string>();
IEnumerable<string> directories = Enumerable.Empty<string>();
try
{
// The test for UnauthorizedAccessException.
var permission = new FileIOPermission(FileIOPermissionAccess.PathDiscovery, rootDirectory);
permission.Demand();
files = Directory.GetFiles(rootDirectory);
directories = Directory.GetDirectories(rootDirectory);
}
catch
{
// Ignore folder (access denied).
rootDirectory = null;
}
foreach (var file in files)
{
yield return file;
}
// Recursive call for SelectMany.
var subdirectoryItems = directories.SelectMany(Traverse);
foreach (var result in subdirectoryItems)
{
yield return result;
}
}
}
}
This code run some time (arround 15secs) but then program crashs.
The error is
System.IO.IOException, process can't access to file C:\hiberfil.sys.
http://upnisito.cz/images/2016_12/319crasherrror.png
Do you have any idea how to solve it?

c# Write DataTable Rows in txt File

I have for like 40 rows on My DataTable Displayed in a DataGridView
i'm confused why my method Saves Only One Row in the TextFile :
private void SaveBtn_Click(object sender, EventArgs e)
{
String outputFile;
List<String> ListData = new List<String>();
using (SaveFileDialog sfd = new SaveFileDialog())
{
sfd.Filter = "Txt File|*.Txt";
if (sfd.ShowDialog() != DialogResult.OK)
return;
outputFile = sfd.FileName;
}
DataTable tb = pw.SavedInfo(User_info.UserID);
for (int i = 0; i < tb.Rows.Count; i++)
{
ListData.Add("Name==> " + tb.Rows[i][1].ToString() + " LastName ==> " + tb.Rows[i][2].ToString() + " Email ==> " + tb.Rows[i][3].ToString() );
}
foreach (String s in ListData)
{
using (TextWriter Tw = new StreamWriter(outputFile))
{
Tw.WriteLine(s);
}
}
}
Did i missed something ? cause it was a really long day to keep being focused
Use the same StreamWriter:
using (TextWriter Tw = new StreamWriter(outputFile))
{
foreach (String s in ListData)
{
Tw.WriteLine(s);
}
}
or use the constructor that takes a bool for "append":
foreach (String s in ListData)
{
using (TextWriter Tw = new StreamWriter(outputFile, true))
{
Tw.WriteLine(s);
}
}
File.WriteAllLines(outputFile, lisData);
Use this to write in the file. File.WriteAllLines Documentation

create zip for more than one file and then upload it into folder

i want to save zip file to server for more than one file only.
first it should create zip file and then upload it to folder
if (FileUpload1.HasFile)
{
string fileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
string fileLocation = Server.MapPath("~/uploads/" + fileName);
FileUpload1.SaveAs(fileLocation);
ZipFile createZipFile = new ZipFile();
createZipFile.AddFile(fileLocation, string.Empty);
createZipFile.Save(Server.MapPath("~/uploads/CsharpAspNetArticles.zip"));
}
If I understood your "noquestion" question :) You should use IHttpHandler like this:
using System;
using System.IO;
using System.Web;
using ICSharpCode.SharpZipLib.Zip;
public class ZipHandler : IHttpHandler
{
public bool IsReusable
{
get { return true; }
}
public void ProcessRequest(HttpContext ctx)
{
var path = HttpUtility.UrlDecode(ctx.Request.QueryString["folder"]);
if (path == null)
{
return;
}
var folderName = Path.GetFileName(path);
if (folderName == String.Empty)
{
folderName = "root";
}
int folderOffset = ctx.Server.MapPath("~").Length;
using (var zipStream = new ZipOutputStream(ctx.Response.OutputStream))
{
ctx.Response.Clear();
ctx.Response.BufferOutput = false;
ctx.Response.AddHeader("Content-Disposition", "attachment; filename=" + folderName + ".zip");
ctx.Response.AddHeader("Content-Type", "application/zip");
zipStream.SetLevel(3);
CompressFolder(path, zipStream, folderOffset);
ctx.Response.Flush();
}
}
private static void CompressFolder(string path, ZipOutputStream zipStream, int folderOffset)
{
string[] files = Directory.GetFiles(path);
foreach (string filename in files)
{
try
{
using (var streamReader = File.OpenRead(filename))
{
var fi = new FileInfo(filename);
string entryName = filename.Substring(folderOffset);
entryName = ZipEntry.CleanName(entryName);
var newEntry = new ZipEntry(entryName)
{
DateTime = fi.LastWriteTime,
Size = fi.Length
};
zipStream.PutNextEntry(newEntry);
streamReader.CopyTo(zipStream, 4096);
zipStream.CloseEntry();
}
}
catch (IOException) { }
}
var folders = Directory.GetDirectories(path);
foreach (string folder in folders)
{
CompressFolder(folder, zipStream, folderOffset);
}
}
}

Categories

Resources