Using Seek Method to read a specific part of a text but it fails.
I have two classes "allmethods.cs" and "caller.cs"
There are two methods in "allmethods.cs" which are "WritingMethod" and "SeekReader"
The program should writes in a text file and read data using seek method in order to read certain part in the text file.
The programs writes smoothly in the text file but it doesn't read anything when calling "SeekReader" which is the seek method.
My Code:
public class allmethods
{
private static string Name;
private static int ID;
private static int Age;
private static string Email;
private static string output;
public static void WritingMethod()
{
int count = 0;
while (count < 10)
{
Console.Write(" Enter your Name: ");
Name = Console.ReadLine();
Console.Write(" Enter your ID: ");
ID = int.Parse(Console.ReadLine());
Console.Write(" Enter your Age: ");
Age = int.Parse(Console.ReadLine());
Console.Write(" Enter your E-mail: ");
Email = Console.ReadLine();
StreamWriter Sw = new StreamWriter("fileone.txt", true);
string output = string.Format("Thank you for registration! Your Submitted information are:" + Environment.NewLine + "Name: {0}"
+ Environment.NewLine + "ID: {1}" + Environment.NewLine + "Age: {2}" + Environment.NewLine + "E-mail: {3}", Name, ID, Age, Email);
Console.WriteLine(output);
Sw.WriteLine(output + Environment.NewLine);
Console.ReadLine();
Sw.Close();
count++;
}
}
public static void SeekReader()
{
FileStream FS=new FileStream("fileone.txt",FileMode.Open,FileAccess.Read);
StreamReader SR = new StreamReader(FS);
SR.BaseStream.Seek(2, SeekOrigin.Begin);
FS.Close();
SR.Close();
}
}
I failed to identify the error. Any suggestions?
Thanks in Advance.
You can use File.ReadAllText([FilePah]) to read the file.
public static void SeekReader()
{
FileStream fsr = new FileStream("fileone.txt", FileMode.Open, FileAccess.Read);
StreamReader Sr = new StreamReader(fsr);
string line = string.Empty;
var ctr = 0;
while(ctr < 3){
line = Sr.ReadLine();
ctr++;
}
Console.WriteLine(line);
Sr.Close();
fsr.Close();
}
Related
I have here a piece of code for my class where I am entering values that are being written into a .txt and .bin file.
My problems are that my .txt file ends up being empty and my .bin file is not writing in binary.
I believe I have written and closed the .bin file and .txt correctly but my inputs are not being stored correctly
Here is my code
static void Main(string[] args)
{
string numberOfStudents, studentName, studentHeight, studentWeight;
int studentInput = 0, height;
bool numberOutput, heightOutput, weightOutput;
double weight;
Console.Write("Enter number of students: ");
numberOfStudents = Console.ReadLine();
numberOutput = int.TryParse(numberOfStudents, out studentInput);
if (numberOutput == true)
{
if (studentInput <= 0)
{
Console.WriteLine("Number of students must be a positive integer (greater than 0)!");
Console.ReadKey();
}
else
{
for (int i = 1; i <= studentInput; i++)
{
Console.Write("Enter student name: ");
studentName = Console.ReadLine();
Console.Write("Enter student height in centimetres: ");
studentHeight = Console.ReadLine();
heightOutput = int.TryParse(studentHeight, out height);
Console.Write("Enter student weight in kilograms: ");
studentWeight = Console.ReadLine();
weightOutput = double.TryParse(studentWeight, out weight);
try
{
StreamWriter outputFile;
outputFile = new StreamWriter("test.txt");
outputFile.Write(numberOfStudents + studentName + studentHeight + studentWeight);
outputFile.Close();
}
catch (System.IO.IOException exc)
{
Console.WriteLine("There was an error!: " + exc.Message);
}
try
{
FileStream outputFile = new FileStream("outFile.bin", FileMode.Create);
BinaryWriter BinFile = new BinaryWriter(outputFile);
BinFile.Write(studentName + " " + studentHeight + " " + studentWeight);
BinFile.Close();
}
catch (System.IO.IOException exc)
{
Console.WriteLine("There was an error!: " + exc.Message);
}
FileStream dataOutput = new FileStream("Database", FileMode.Create);
BinaryWriter databaseFile = new BinaryWriter(dataOutput);
StreamWriter textOutput = new StreamWriter("outText.txt");
databaseFile.Write(studentName + " " + studentHeight + " " + studentWeight);
databaseFile.Close();
textOutput.Close();
}
}
}
Thank you
You're almost there but there are a few issues with the code and it could be tidied up a little.
You are creating 3 files: outFile.bin, outText.txt, and test.txt. No data/text is written to outFile.txt, it is opened then closed a few lines later. Look in test.txt, it will have the last students data (see next point).
You are writing the files in a loop, which is overwriting the data, so only the last users data is being written to the file. Use outputFile = new StreamWriter("test.txt", true) this overload of StreamWriter will allow you to choose to append to the file (true) or overwrite (false).
I'd recommend looking at the using() statement when writing to file or any class that implements IDisposable. For example, when opening the StreamWriter you could do using (var outputFile = new StreamWriter("test.txt", true)) { }. This ensures the streamwriter is closed and disposed by the garbage collector, (For example, you are not closing the dataOutput file stream, if this was in a using(){} block it would automatically be handled for you)
This could be refactored into using just one try {} catch {} block, you do not need a separate try/catch for each time you write to a file.
From the Docs, the BinaryWriter class
Writes primitive types in binary to a stream and supports writing strings in a specific encoding.
So, the binary writer is writing in binary, but the data it's writing are strings. It could easily write int, double, bool, etc.
Here's the code in your try/catch blocks tidied up a bit (this only creates test.txt and outFile.bin):
try
{
// will open or create file in 'append' mode
using (var outputFile = new StreamWriter("test.txt", true))
{
outputFile.Write($"{numberOfStudents}, {studentName}, {studentHeight},{studentWeight}");
outputFile.Write(Environment.NewLine);
}
using (BinaryWriter databaseFile = new BinaryWriter(File.Open("outFile.bin", FileMode.Append)))
{
databaseFile.Write(studentName + " " + studentHeight + " " + studentWeight);
}
}
catch (System.IO.IOException exc)
{
Console.WriteLine("There was an error!: " + exc.Message);
}
I'm writing a program to find a md5 hash that has a hexadecimal representation with the digits of pi. I got a problem on saving the computations. It looks like the program won't save the string correctly. It makes a long string rather than replacing the old one. How can I fix that problem?
public static string get_last_string()
{
string text;
string text2="";
int i= 0;
string path = "C:\\Users\\uname\\Desktop";
var fileStream = new FileStream(#path + "\\last.txt", FileMode.Open, FileAccess.Read);
using (var streamReader = new StreamReader(fileStream, Encoding.UTF8))
{
text = streamReader.ReadToEnd();
}
i=0;
while (i < text.Length && text[i] != ' ')
{
text2 += text[i];
++i;
}
return text2;
}
public static void Main(string[] args)
{
string path = #"C:\Users\Uname\Desktop\test.txt";
string a = get_last_string();
Console.WriteLine("Let us continue from the string " + a);
Console.WriteLine("Ctrl+C stops the computing and saves the results to the file last.txt");
do
{
while (!Console.KeyAvailable)
{
// Console.WriteLine("md5("+a+")="+CalculateMD5Hash(a));
if (CommonPrefix(CalculateMD5Hash(a), "314159265353") >= 11)
{
Console.WriteLine(a + " " + CalculateMD5Hash(a));
File.WriteAllText(path, a + " " + CalculateMD5Hash(a));
}
a = Next(a);
}
} while (Console.ReadKey(true).Key != ConsoleKey.Escape);
File.AppendAllText(#path + "\\last.txt", a);
}
You have a File.WriteAllText(... and later on you have File.AppendAllText(...
I'm pretty shure you're writing twice to the file.
I am trying to pass a file to method based on the selections of an int and converting the result via a case and using the fileName in a StreamReader so that it is dynamic and not a constant, allowing the user to change.
this is what I have so far,
Menu:
public static void DrawHeading()
{
DrawBlankLine();
DrawLine();
DrawBlankLine();
Console.WriteLine("* Poker Hand Evaluation *");
DrawLine();
}
public static void MenuContent(int maxItems)
{
DrawBlankLine();
Console.WriteLine(" 1. File: Flush.txt");
Console.WriteLine(" 2. File: FourKind.txt");
Console.WriteLine(" 3. File: FullHouse.txt");
Console.WriteLine(" 4. File: Pair.txt");
Console.WriteLine(" 5. File: RoyalFlush.txt");
Console.WriteLine(" 6. File: Straight.txt");
Console.WriteLine(" 7. File: StraightFlush.txt");
Console.WriteLine(" 8. File: ThreeKind.txt");
Console.WriteLine(" 9. File: TwoPair.txt");
Console.WriteLine(" 10. Enter file name");
Console.WriteLine(" {0}. Exit program", maxItems);
DrawBlankLine();
Console.WriteLine("Make your choice: "
+ "Please type 1, 2,... or {0} for exit.", maxItems);
DrawBlankLine();
DrawLine();
DrawBlankLine();
}
public static void DisplayMenu()
{
const int MAX_MENU_ITEMS = 11;
bool maxMenu = false;
int getMenuSelection = 0;
string fileName = null;
while (getMenuSelection != MAX_MENU_ITEMS)
{
Console.Clear();
DrawHeading();
MenuContent(MAX_MENU_ITEMS);
maxMenu = int.TryParse(Console.ReadLine(), out getMenuSelection);
if (maxMenu)
{
switch (getMenuSelection)
{
case 1:
fileName = "RoyalFlush.txt";
Console.WriteLine("File Name: {0}", fileName);
break;
case 2:
fileName = "StraightFlush.txt";
break;
case 3:
fileName = "FourKind.txt";
break;
case 4:
fileName = "FullHouse.txt";
break;
case 5:
fileName = "Flush.txt";
break;
case 6:
fileName = "Straight.txt";
break;
case 7:
fileName = "ThreeKind.txt"; ;
break;
case 8:
fileName = "TwoPair.txt"; ;
break;
case 9:
fileName = "Pair.txt"; ;
break;
case 10:
Case10();
break;
case 11:
Console.WriteLine("Exiting program...");
System.Environment.Exit(0);
break;
default:
if (getMenuSelection != MAX_MENU_ITEMS)
{
MenuErrorMessage();
}
break;
}
//return fileName;
}
else
{
MenuErrorMessage();
}
Console.ReadLine();
}
//return fileName;
}
Method when fileName is to be used:
public static void LoadHand(Card[] data)
{
string fileName = null;
Console.WriteLine("file name: {0}", fileName);
Console.ReadLine();
string input = fileName;
List<Card> cards = new List<Card>();
StreamReader inFile = new StreamReader(fileName);//open file
code for void LoadHand
this is what I have:
public static void LoadHand(Card[] data)
{
string fileName = null;
Console.WriteLine("file name: {0}", fileName);
Console.ReadLine();
string input = fileName;
List<Card> cards = new List<Card>();
StreamReader inFile = new StreamReader(fileName);//open file
input = inFile.ReadLine();//priming read for array
string[] inputArray = input.Split(new char[] { ' ' },
StringSplitOptions.RemoveEmptyEntries);
//input loading file content into array of structures
for (int i = 0; i < data.Length; ++i)
{
Card newCard = new Card();
newCard.suit = inputArray[i * 2][0];
newCard.value = int.Parse(inputArray[i * 2 + 1]);
data[i] = newCard;
}
inFile.Close();//Close file
}'
Change the signature of DisplayMenu to static string DisplayMenu()
Remove the comments (//) on return fileName; in DisplayMenu.
Add fileName as an argument to LoadHand
public static void LoadHand(Card[] data, string path)
{
List<Card> cards = new List<Card>();
StreamReader inFile = new StreamReader(path);//open file
I've been working on my module exercises and I came across this code snippet which reads the text file and prints the details about it.
It's working fine, but I just want to know how to give the path of the text file in the code itself other than giving the path in the command line.
Below is my code.
class Module06
{
public static void Exercise01(string[] args)
{
string fileName = args[0];
FileStream stream = new FileStream(fileName, FileMode.Open);
StreamReader reader = new StreamReader(stream);
int size = (int)stream.Length;
char[] contents = new char[size];
for (int i = 0; i < size; i++)
{
contents[i] = (char)reader.Read();
}
reader.Close();
Summarize(contents);
}
static void Summarize(char[] contents)
{
int vowels = 0, consonants = 0, lines = 0;
foreach (char current in contents)
{
if (Char.IsLetter(current))
{
if ("AEIOUaeiou".IndexOf(current) != -1)
{
vowels++;
}
else
{
consonants++;
}
}
else if (current == '\n')
{
lines++;
}
}
Console.WriteLine("Total no of characters: {0}", contents.Length);
Console.WriteLine("Total no of vowels : {0}", vowels);
Console.WriteLine("Total no of consonants: {0}", consonants);
Console.WriteLine("Total no of lines : {0}", lines);
}
}
In your static void Main, call
string[] args = {"filename.txt"};
Module06.Exercise01(args);
Reading of a text file is much easier with File.ReadAllText then you don't need to think about closing the file you just use it. It accepts file name as parameter.
string fileContent = File.ReadAllText("path to my file");
string fileName = #"path\to\file.txt";
This is a WinForm written in C#.
Lets say I'm generating a random named text file in my selected directory. When the button is clicked teh first time, i write the data contained in the textboxes into that text file. If the user wants to do the same thing with different data in the textboxes then the click on the button should write the new data into the text file without losing the old data. It's like keeping logs, is this possible?
My code is like:
private readonly Random setere = new Random();
private const string chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
private string RandomString()
{
char[] buffer = new char[5];
for (int i = 0; i < 5; i++)
{
buffer[i] = chars[setere.Next(chars.Length)];
}
return new string(buffer);
}
private void button1_Click(object sender, EventArgs e)
{
DialogResult dia = MessageBox.Show("Wanna continue?", "Question", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (dia == DialogResult.Yes)
{
StreamWriter wFile = new StreamWriter("C:\\Users\\Ece\\Documents\\Testings\\" + RandomString() + ".txt");
wFile.WriteLine("Name Surname:" + text1.Text + text2.Text);
wFile.WriteLine("Other:" + text3.Text + text4.Text);
wFile.WriteLine("Money:" + textBox1.Text + " TL.");
wFile.WriteLine("*************************************");
wFile.Close();
}
else
{
return;
}
}
You can append to the text in the file.
See
File.AppendText
using (StreamWriter sw = File.AppendText(pathofFile))
{
sw.WriteLine("This");
sw.WriteLine("is Extra");
sw.WriteLine("Text");
}
where pathofFile is the path to the file to append to.
Have a look at using something like this:
StreamWriter fw = new StreamWriter(#"C:\Logs\MyFile.txt",true);
fw.WriteLine("Some Message" + Environment.Newline);
fw.Flush();
fw.Close();
Hope that helps. See MSDN StreamWriter for more information
Updated: Removed old example
Also if you are trying to create a unique file you can use Path.GetRandomFileName()
Again from the MSDN Books:
The GetRandomFileName method returns a
cryptographically strong, random
string that can be used as either a
folder name or a file name.
UPDATED: Added a Logger class example below
Add a new class to your project and add the following lines (this is 3.0 type syntax so you may have to adjust if creating a 2.0 version)
using System;
using System.IO;
namespace LogProvider
{
//
// Example Logger Class
//
public class Logging
{
public static string LogDir { get; set; }
public static string LogFile { get; set; }
private static readonly Random setere = new Random();
private const string chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
public Logging() {
LogDir = null;
LogFile = null;
}
public static string RandomFileName()
{
char[] buffer = new char[5];
for (int i = 0; i < 5; i++)
{
buffer[i] = chars[setere.Next(chars.Length)];
}
return new string(buffer);
}
public static void AddLog(String msg)
{
String tstamp = Convert.ToString(DateTime.Now.Day) + "/" +
Convert.ToString(DateTime.Now.Month) + "/" +
Convert.ToString(DateTime.Now.Year) + " " +
Convert.ToString(DateTime.Now.Hour) + ":" +
Convert.ToString(DateTime.Now.Minute) + ":" +
Convert.ToString(DateTime.Now.Second);
if(LogDir == null || LogFile == null)
{
throw new ArgumentException("Null arguments supplied");
}
String logFile = LogDir + "\\" + LogFile;
String rmsg = tstamp + "," + msg;
StreamWriter sw = new StreamWriter(logFile, true);
sw.WriteLine(rmsg);
sw.Flush();
sw.Close();
}
}
}
Add this to your forms onload event
LogProvider.Logging.LogDir = "C:\\Users\\Ece\\Documents\\Testings";
LogProvider.Logging.LogFile = LogProvider.Logging.RandomFileName();
Now adjust your button click event to be like the following:
DialogResult dia = MessageBox.Show("Wanna continue?", "Question", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (dia == DialogResult.Yes)
{
StringBuilder logMsg = new StringBuilder();
logMsg.Append("Name Surname:" + text1.Text + text2.Text + Environment.NewLine);
logMsg.Append("Other:" + text3.Text + text4.Text + Environment.NewLine);
logMsg.Append("Money:" + textBox1.Text + " TL." + Environment.NewLine);
logMsg.Append("*************************************" + Environment.NewLine);
LogProvider.Logging.AddLog(logMsg.ToString());
} else
{
return;
}
Now you should only create one file for the entire time that application is running and will log to that one file every time you click your button.
You might want to take a look at log4net and the RollingFileAppender
Sure. Just open the file for appending with something like System.IO.File.AppendText