Display Output in a text file - c#

I have taken the input code through file and i have to generate data according to it and output it's result in a text file as well..
My Output Code is below..
public void Generator()
{
/// ....... Code
public void DisplayTOKENS()
{
using (StreamWriter writer =
new StreamWriter("C:\\Users\\saeed\\Documents\\Outputt.txt"))
{
for (int i = 0; i < j;i++ )
{
tok[i].Display_Token();
} }
}
// and in other structur named TOKEN
public void Display_Token()
{ /*
using (StreamWriter writer =
new StreamWriter("C:\\Users\\saeed\\Documents\\Outputt.txt"))
{
writer.Write("( " + this.Class_Part + " , ");
writer.Write(this.Value_Part + " , ");
writer.Write(this.Line_no + " )");
writer.WriteLine();
}*/
Console.Write("( " + this.Class_Part + " , ");
Console.Write(this.Value_Part + " , ");
Console.Write(this.Line_no + " )");
Console.WriteLine();
}
When i try to directly work in Display_Token then it just simply show the last line in file.. i want to display the complete array in the file. waiting for some positive response !!

That StreamWriter constructor overwrites the existing file. So, each token effectively deletes whatever was written earlier then writes its content. That is why you only see the last token's content in the file.
Use the overload with the "append" argument and pass true so that the existing file is not deleted.

You have to check if file exists and than do "append" operation instead of "overwrite".
// in DisplayTOKENS()
string fileName = "C:\\Users\\saeed\\Documents\\Outputt.txt";
if (System.IO.File.Exists(fileName))
System.IO.File.Delete(fileName);
for (int i = 0; i < j; i++)
{
tok[i].Display_Token(fileName);
}
// in Display_Token(string fileName)
System.IO.File.AppendAllText(fileName, "( " + this.Class_Part + " , " + this.Value_Part + " , " + this.Line_no + " )");

Related

Save and load array in and from a file

I need to save multidimensional array into file. Then be able to change things in that so it will also appear in that file and load from said file into array.
Let's say I have some array:
private string[,] array = new string[5, 5];
Then I need to do a function, that will fill the array with space if file does not exist and if it does, load it. Something like this:
private void Load()
{
if (File.Exists("save.txt"))
{
}
else
{
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 5; j++)
{
array[i,j] = " ";
}
}
}
}
I checked if the file exists, if not I will fill the array with spaces but then I need in some way write the array in the file in this format:
" ", " ", " "," ", " ",
" ", " ", " "," ", " ",
" ", " ", " "," ", " ",
" ", " ", " "," ", " ",
" ", " ", " "," ", " ",
or in some format, that will work.
Then I basically planned to split the string with ',' and save it to that array. And if file exists, read it and save the values to said array.
So basically I need to check if the file exist, if the answer is yes, load it to the multidimensional array, If the answer is no, fill the array with empty strings and load that in the file.
If somebody is willing to help me, I will be very grateful.

C# out of memory with file

I'm getting a OutOfMemory exception when running the following code, it happens on the File.ReadLines line, it processes most files fine until it hits larger files.
It's consistantly using tons of memory and cpu during the whole process though.
The file it crashed on is only 156,000KB, which is 156mb
static void Main(string[] args)
{
Console.CursorVisible = false;
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine();
Console.WriteLine(" [" + DateTime.Now.ToShortTimeString() + "]" + " Connected to the Cassandra Database");
Console.WriteLine();
Console.ForegroundColor = ConsoleColor.White;
string filepath = #"C:\Users\admin\Desktop\wecrack lists";
DirectoryInfo directory = new DirectoryInfo(filepath);
int fileCount = 0;
var client = new MongoClient("mongodb://localhost:27017");
var database = client.GetDatabase("cracking");
var collection = database.GetCollection<Password>("passwords");
foreach (var file in directory.GetFiles("*"))
{
fileCount++;
Console.WriteLine(" [" + DateTime.Now.ToShortTimeString() + "]" + " Working through file: {" + file + "} {" + fileCount + "/" + directory.GetFiles("*").Count() + "}");
List<Password> entitys = new List<Password>();
foreach (string line in File.ReadLines(filepath + #"\" + file.ToString()))
{
entitys.Add(new Password { password = line });
}
collection.InsertManyAsync(entitys);
}
Console.WriteLine();
Console.WriteLine(" [" + DateTime.Now.ToShortTimeString() + "]" + " Finished inserting records, press any key to get the count.");
Console.ReadKey(true);
while (true)
{
Console.ReadKey(true);
}
}
Try batching your updates. That way you won't have all that data in memory at the same time. It may also help you not totally lock up your database.
...
foreach (var file in directory.GetFiles("*"))
{
fileCount++;
Console.WriteLine(" [" + DateTime.Now.ToShortTimeString() + "]" + " Working through file: {" + file + "} {" + fileCount + "/" + directory.GetFiles("*").Count() + "}");
System.IO.StreamReader file = new System.IO.StreamReader(filepath + #"\" + file.ToString());
while(!file.EndOfStream)
{
int passwordBatchCount = 0;
List<Password> entitysBatch = new List<Password>();
while ((string line = file.ReadLine()) != null && passwordBatchCount < BATCH_SIZE)
{
entitysBatch.Add(new Password { password = line });
passwordBatchCount++;
}
collection.InsertManyAsync(entitysBatch);
}
file.Close();
}
}
...

C# compare id from text file in filestream

I need to fill a text file with information about workers. Then I need to read from the file and search for an ID that user tries to find. For example my file contains ids 1,2,3 and if I try to find id 3 and it matches, then this worker's all information is written in console. Otherwise it writes a text A worker cannot be found.
using System;
using System.IO;
class Program
{
static void Main(string[] args)
{
string file = "C:\\Temp\\registery.txt";
FileStream fOutStream = File.Open(file, FileMode.Append, FileAccess.Write);
StreamWriter sWriter = new StreamWriter(fOutStream);
int[] id = { 1, 2, 3 };
string[] name = { "John", "Carl", "Thomas" };
float[] salary = { 3500, 4800, 2100 };
for (int i = 0; i < id.Length; i++)
{
sWriter.WriteLine(id[i] + " " + name[i] + " " + salary[i]);
}
sWriter.Flush();
sWriter.Close();
FileStream fInStream = File.OpenRead(file);
StreamReader sReader = new StreamReader(fInStream);
int id2;
Console.WriteLine("Type worker's id");
id2 = int.Parse(Console.ReadLine());
bool a;
a = sReader.ReadToEnd().Contains(id2);
Console.WriteLine(a);
sReader.Close();
}
}
If you want to create a text file to be searchable, it should be delimited by a separator like comma /TAB
so modify your code:
sWriter.WriteLine(id[i] + "," + name[i] + "," + salary[i]);
To search your text file by id/name/..whatever and use AND/OR, you can use the method described here:
How would I convert data in a .txt file into xml? c#
BTW: Re-factor your code to create the file in a separate method, and the search in other one.
I found a solution myself to my problem and it worked good enough. It might not be the best solution. I removed bool things and I replaced the whole thing with this:
string line;
while ((line = sReader.ReadLine()) != null)
{
if (line.Contains("id: " + id2))
{
Console.WriteLine(line);
break;
}
else if ((line = sReader.ReadLine()) == null)
{
Console.WriteLine("Worker not found with id " + id2);
}
}
And I fixed the upper for loop to look like this:
sWriter.WriteLine("id: " + id[i] + " name: " + name[i] + " salary: " + salary[i]);

exiting console application c# and writing to log

So I'm trying to exit a console application IF a parameter check fails, however, I still want it to log to a file. The logging to a file works fine as long as all the parameters are good. However, when a parameter check fails and hits the System.Environment.Exit(0) portion, the log file is still completely empty. Here's the code so far. Please help, I've tried everything I could think of.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace I2C_File_Splitter
{
class Program
{
static void Main(string[] args)
{
//get command line input paramaters
using (StreamWriter log = File.AppendText("Splitter_log.txt"))
{
log.WriteLine(DateTime.Now + " ******************************************** SPLITTER STARTED ****************************************************************");
log.WriteLine(DateTime.Now + " FILE: " + args[0] + " DESTINATION: " + args[1] + " MAX COUNT PER FILE: " + args[2]);
if (args.Length == 0)
System.Environment.Exit(0);
string originalFile = args[0];
string destination = args[1];
int fileLength = Convert.ToInt32(args[2]);
string fileName;
string fileExtension;
string line;
int fileNumber = 1;
if (!File.Exists(originalFile))
{
log.WriteLine(DateTime.Now + " Error: Transfund file not found for: " + args[0]);
log.WriteLine(DateTime.Now + " ******************************************** SPLITTER ENDED ****************************************************************");
System.Environment.Exit(0);
}
if (!Directory.Exists(destination))
{
log.WriteLine(DateTime.Now + " Error: destination directory not found for: " + args[1] );
log.WriteLine(DateTime.Now + " ******************************************** SPLITTER ENDED ****************************************************************");
System.Environment.Exit(0);
}
if (fileLength < 0)
{
log.WriteLine(DateTime.Now + " Error: file length must be greater than 0. Incorrect value " + args[2]);
log.WriteLine(DateTime.Now + " ******************************************** SPLITTER ENDED ****************************************************************");
System.Environment.Exit(0);
}
//get file name and file extension
fileName = Path.GetFileNameWithoutExtension(originalFile);
fileExtension = Path.GetExtension(originalFile);
StreamReader file = new StreamReader(originalFile);
log.WriteLine(DateTime.Now + " processing: " + fileName);
string header = file.ReadLine(); //get first line
while ((line = file.ReadLine()) != null)
{
StreamWriter newFile = new StreamWriter(destination + "\\" + fileName + "_" + fileNumber.ToString() + fileExtension);
newFile.WriteLine(header);
newFile.WriteLine(line);
int counter = 1;
while (counter < fileLength)
{
line = file.ReadLine();
if (line == null)
break;
newFile.WriteLine(line);
counter++;
}
newFile.Close();
log.WriteLine(DateTime.Now + " " + fileName + "_" + fileNumber.ToString() + fileExtension + " created. Card count: " + counter);
fileNumber++;
}
log.WriteLine(DateTime.Now + " Processing completed: " + fileName);
log.WriteLine(DateTime.Now + " ******************************************** SPLITTER ENDED ****************************************************************");
}
}
}
}
When you call Environment.Exit, you're telling it to terminate your program immediately.
Your "log" stream never gets flushed (which would happen when you reach the end of the using block), and so nothing gets a chance to be written to the file.
Try flushing the stream before calling exit.
if (!Directory.Exists(destination))
{
log.WriteLine(DateTime.Now + " Error: destination directory not found for: " + args[1] );
log.WriteLine(DateTime.Now + " ******************************************** SPLITTER ENDED ****************************************************************");
// write all pending log messages to the file
log.Flush();
System.Environment.Exit(0);
}

Putting certain lines of a textfile into an editable listbox

So I want to put certain lines into a text box, say I use the "Search Function" to search transaction ID, it would look through the transactions.txt file and find the transaction ID and Read the 6 lines under it which show the transactions Details, once found this would then go to a the listbox which then you could edit the transaction.
I was wondering would you use loops and arrays to do this, and could someone show me how, Thank you!
Heres my current code:
//Creates a textfile with details of the transaction
public void CreateFile()
{
StreamWriter outputFile;
outputFile = File.AppendText("Transactions.txt");
outputFile.WriteLine("Investor :" +" " + InvestorNameLabel.Text);
outputFile.WriteLine("Initial Amount" + " " +AmountLabel.Text);
outputFile.WriteLine("Date Invested" +" " +DateLabel.Text);
outputFile.WriteLine("Period Chosen" + " "+DaysInvestedLabel.Text);
outputFile.WriteLine("Rate Chosen" + " " + RateLabel.Text);
outputFile.WriteLine("Total Interest" + " " +InterestAmountLabel.Text);
outputFile.WriteLine("Transaction Number :" + " " + TransactionIDLabel.Text);
outputFile.Close();
MessageBox.Show("Transaction file for Transaction: " + TransactionIDLabel.Text + " " +"Was Created", "Transaction File");
}
//puts all transactions in listbox
//needs to be able to find certain transactions
private void button1_Click(object sender, EventArgs e)
{
using (StreamReader sr = new StreamReader("transactions.txt"))
{
string line;
while ((line = sr.ReadLine()) != null)
{
listBox1.Items.Add(line);
}
}
}
Try This:
string ID = "23";
bool idFound=false;
int count = 0;
foreach (var line in File.ReadLines("transactions.txt"))
{
if (idFound && count < 6)
{
listBox1.Items.Add(line);
count++;
}
if(line.Contains(ID))//if you wantto match exactly use if(line.Equals(ID))
{
idFound = true;
}
}

Categories

Resources