How I can access a file with c#? [duplicate] - c#

This question already has answers here:
How to read an entire file to a string using C#?
(17 answers)
Closed 3 years ago.
There are some function that read all text from file without use FileStream class and more easy?
In microsoft doc found this code to read from file but I think is some complexed.
private async void Button_Click_1(object sender, RoutedEventArgs e)
{
string filename = #"C:\Example\existingfile.txt";
char[] result;
StringBuilder builder = new StringBuilder();
using (StreamReader reader = File.OpenText(filename))
{
result = new char[reader.BaseStream.Length];
await reader.ReadAsync(result, 0, (int)reader.BaseStream.Length);
}
foreach (char c in result)
{
if (char.IsLetterOrDigit(c) || char.IsWhiteSpace(c))
{
builder.Append(c);
}
}
FileOutput.Text = builder.ToString();
}

Please see the File.ReadAllText Method.
public static void Main()
{
string path = #"c:\temp\MyTest.txt";
// This text is added only once to the file.
if (!File.Exists(path))
{
// Create a file to write to.
string createText = "Hello and Welcome" + Environment.NewLine;
File.WriteAllText(path, createText, Encoding.UTF8);
}
// This text is always added, making the file longer over time
// if it is not deleted.
string appendText = "This is extra text" + Environment.NewLine;
File.AppendAllText(path, appendText, Encoding.UTF8);
// Open the file to read from.
string readText = File.ReadAllText(path);
Console.WriteLine(readText);
}

Related

Counting the # of lines in a very large file gives System OutofMemory Exception [duplicate]

This question already has answers here:
What's the fastest way to read a text file line-by-line?
(9 answers)
Closed 5 years ago.
static void Main(string[] args)
{
string TheDataFile = "";
string ErrorMsg = "";
string lngTransDate = "";
ProcessDataFile ProcessTheDataFile = new ProcessDataFile();
string TheFile = "S:\\MIS\\Provider NPI file\\Processed\\npidata_20050523-20161009.csv";
string[] lines = File.ReadAllLines(TheFile, Encoding.UTF8);//Read all lines to an array
Console.WriteLine(lines.Length.ToString());
Console.ReadLine();
}
This throws an error because the file is very large (has 6 million lines). Is there a way to handle large files and count the # of lines?
Use a StreamReader:
string TheFile = "S:\\MIS\\Provider NPI file\\Processed\\npidata_20050523-20161009.csv";
int count = 0;
using (System.IO.StreamReader sr = new System.IO.StreamReader(TheFile))
{
while (sr.ReadLine() != null)
count++;
}
You need to do a lazy evaluation of the file so it isn't loaded into memory entirelly.
Helper method
public static class ToolsEx
{
public static IEnumerable<string> ReadAsLines(this string filename)
{
using (var streamReader = new StreamReader(filename))
while (!streamReader.EndOfStream)
yield return streamReader.ReadLine();
}
}
Usage
var lineCount = "yourfile.txt".ReadAsLines().Count();
According to this already accepted answer, this should do it.
using System;
using System.IO;
namespace CountLinesInFiles_45194927
{
class Program
{
static void Main(string[] args)
{
int counter = 0;
foreach (var line in File.ReadLines("c:\\Path\\To\\File.whatever"))
{
counter++;
}
Console.WriteLine(counter);
Console.ReadLine();
}
}
}

How to append text to all existing .txt documents in C#?

So I have this code:
class Program
{
static void Main(string[] args)
{
// Set a variable to the My Documents path.
string mydocpath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
var dir = new DirectoryInfo(mydocpath + #"\sample\");
string msg = "Created by: Johny";
foreach (var file in dir.EnumerateFiles("*.txt"))
{
file.AppendText(msg); //getting error here
}
}
}
And I want to add a footer to all the text file in the sample folder, but I'm getting an error because the AppendText is not accepting a string argument. I was just wondering how do I do this?
You want to use the streamwriter from AppendText I think:
static void Main(string[] args)
{
// Set a variable to the My Documents path.
string mydocpath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
var dir = new DirectoryInfo(mydocpath + #"\sample\");
string msg = "Created by: Johny";
foreach (var file in dir.EnumerateFiles("*.txt"))
{
var streamWriter = file.AppendText();
streamWriter.Write(msg);
streamWriter.Close();
}
}
FileInfo.AppendText() creates a StreamWriter, it doesn't append text per se. You want to do this:
using (var sw = file.AppendText()) {
sw.Write(msg);
}
AppendText is the extension method for the StreamWriter, see the documentation
So you should write these code instead:
foreach (var file in dir.EnumerateFiles("*.txt"))
{
using (StreamWriter sw = File.AppendText(file.FullName))
{
sw.WriteLine(msg);
}
}

Only write data to text file if the line doesnt match any others

I want to add data into a text file based on a specific output. It will read an XML file and write a certain line to a text file. If the data is already written into the text file, I don't want to write it again.
Code
public void output(string folder)
{
string S = "Data" + DateTime.Now.ToString("yyyyMMddHHmm") + ".xml";
//Trades.Save(S);
string path = Path.Combine(folder, S);
Console.WriteLine(path);
XDocument f = new XDocument(Trades);
f.Save(path);
string[] lines = File.ReadAllLines(path);
File.WriteAllLines(path, lines);
using (System.IO.StreamWriter file = new System.IO.StreamWriter(
#"H:\Test" + DateTime.Now.ToString("yyMMdd") + ".txt", true))
{
foreach (string line in lines)
{
if (line.Contains("CertainData"))
{
file.WriteLine(line);
if (File.ReadAllLines(path).Any(x => x.Equals(line)))
{
}
else
{
string[] tradeRefLines = File.ReadAllLines(path);
File.WriteAllLines(path, tradeRefLines); ;
}
}
}
}
}
The problem is it will still write the line even if the data is exactly the same elsewhere. I don't want duplicate lines.
Any advice?
Edit
The CertainData is a reference number.
I have a bunch of files that have data in them and the piece I want to seperate and put into a text file is CertainData field, which will have a reference number.
Sometimes the files I get sent will have the same formatted information inside it with the CertainData appearing in them for reference.
When i run this programme, if the text file i have already contains the "CertainData" reference number inside it, i dont want it to be written
If you need anymore clarification let me know and i will update the post
Try with this LINQ:
var previousLines = new HashSet<string>();
File.WriteAllLines(destPath, File.ReadLines(sourcePath)
.Where(line => previousLines.Add(line)));
EDITED :
public void output(string folder)
{
string S = "Data" + DateTime.Now.ToString("yyyyMMddHHmm") + ".xml";
//Trades.Save(S);
string path = Path.Combine(folder, S);
Console.WriteLine(path);
XDocument f = new XDocument(Trades);
f.Save(path);
string[] lines = File.ReadAllLines(path);
File.WriteAllLines(path, lines);
bool isExist = false;
using (System.IO.StreamWriter file = new System.IO.StreamWriter(#"H:\Test" + DateTime.Now.ToString("yyMMdd") + ".txt", true))
{
foreach (string line in lines)
{
if (line.Contains("CertainData"))
{
isExist = true;
}
}
if (!isExist)
{
File.AppendAllText(path, "CertainData" + Environment.NewLine);
}
}
}

OutOfMemoryException contents of files [duplicate]

This question already has answers here:
Read Big TXT File, Out of Memory Exception
(6 answers)
Closed 8 years ago.
I have the following code which loads the contents of the file to memory but I want a better way as I am getting the following error
Unhandled Exception: OutOfMemoryException.
Is there a more efficient way of handling this most files I am going to be looking through are 1.85 GB
class Program
{
public static string sDate;
public static string sTerm;
static void Main(string[] args)
{
Console.WriteLine("Enter the date to search - yyyy-mm-dd");
sDate = Console.ReadLine();
Console.WriteLine("Enter search term");
sTerm = Console.ReadLine();
DirectoryInfo di = new DirectoryInfo(Environment.GetEnvironmentVariable("ININ_TRACE_ROOT") + "\\" + sDate + "\\");
FileInfo[] files = di.GetFiles("*.ininlog");
foreach (FileInfo file in files)
{
using (StreamReader sr = new StreamReader(file.FullName))
{
string content = sr.ReadToEnd();
if (content.Contains(sTerm))
{
Console.WriteLine("{0} contains\"{1}\"", file.Name, sTerm);
}
}
}
}
}
You can use StreamReader.ReadLine to process the file line-by-line.
using (StreamReader sr = new StreamReader(file.FullName))
{
string line;
while((line = sr.ReadLine()) != null)
{
if (line.Contains(sTerm))
{
Console.WriteLine("{0} contains\"{1}\"", file.Name, sTerm);
break;
}
}
}

IoException while writing in text file in c#

I have text file which i need to update according to the regex match but as soon as my program tries to write a line into text file it is giving following error..
The process cannot access the file 'D:\Archieve\20140123.text' because it is being used by another process.
Here is my C# code..
static void Main(string[] args)
{
string textfilename="";
string strDateTime = DateTime.Now.ToString("yyyyMMdd");
string strformatedatetime = DateTime.Now.ToString("yyyy/MM/dd");
if (strDateTime != "") {
string loc = "D:\\Archieve\\";
string date=strDateTime;
string text=".text";
textfilename = loc + date + text;
File.Create(textfilename);
}
string pattern = "^" + strformatedatetime + ".*";
string FileToCopy = "D:\\ipdata.txt";
string NewCopy =textfilename;
StringBuilder sb = new StringBuilder("");
List<string> newLines = new List<string>();
if (System.IO.File.Exists(FileToCopy) == true)
{
string[] lines = File.ReadAllLines(FileToCopy);
foreach (string line in lines)
{
if (Regex.IsMatch(line, pattern))
{
sb.Append(line + System.Environment.NewLine);
TextWriter tsw = new StreamWriter(textfilename,true);
//Writing text to the file.
tsw.WriteLine(sb);
//Close the file.
tsw.Close();
}
}
}
}
I am getting above defined error at this line of code...
TextWriter tsw = new StreamWriter(textfilename,true);
Where am i going wrong ?
You don't need to have a separate instruction to create a file.
The StreamWriter will take care of it: Here is the description of the constructor you user
> Initializes a new instance of the StreamWriter class for the specified
> file by using the default encoding and buffer size. If the file
> exists, it can be either overwritten or appended to. If the file does
> not exist, this constructor creates a new file.
Use File.Create(textfilename).Close();
As the error message suggests

Categories

Resources