Passing File Name Variable to Method for Use - c#

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

Related

How do I add parsed lines into a dictionary?

I am trying to make a dictionary where the compiler reads from a text file where there are two words per line. I have parsed it through the split() method but I am struggling on how to add the corresponding keys and values from the line to the dictionary container. I am trying to add it in the ReadStream2() function after doing the split() in the line line.add(rez,rez). I know this is wrong but I have no idea how to combine what I am parsing into the dictionary in terms of keys and values. Thanks!
class Program
{
static void Main(string[] args)
{
Dictionary<string, string> line = new Dictionary<string, string>();
FileStream filestream = null;
string path = "Dictionary.txt";
//WriteByte(filestream, path);
//ReadByte(filestream, path);
//WriteStream(filestream, path);
//ReadFromFile();
Menu(filestream, path);
ReadStream2(filestream,path);
Group(filestream, path);
}
static void WriteByte(FileStream filestream, string path)
{
string str;
Console.WriteLine("Enter word");
str = Console.ReadLine();
try
{
filestream = new FileStream("Dictionary.txt", FileMode.Open, FileAccess.Write);
byte[] by = Encoding.Default.GetBytes(str);
filestream.Write(by, 0, by.Length);
Console.WriteLine("File written");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
filestream.Close();
}
}
static void ReadByte(FileStream filestream, string path)
{
try
{
filestream = new FileStream(path, FileMode.Open, FileAccess.Read);
byte[] by = new byte[(int)filestream.Length];
filestream.Read(by, 0, by.Length);
string str = Encoding.Default.GetString(by);
Console.WriteLine("File read");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
filestream.Close();
}
}
static void WriteStream(FileStream filestream, string path)
{
using (filestream = new FileStream(path, FileMode.Append, FileAccess.Write))
{
using (StreamWriter streamWriter = new StreamWriter(filestream))
{
//string str;
//Console.WriteLine("Enter word");
//str = Console.ReadLine();
//streamWriter.WriteLine(str);
}
}
}
static void ReadStream2(FileStream fileStream, string path)
{
using (fileStream = new FileStream(path, FileMode.Open, FileAccess.Read))
{
Dictionary<string, string> line = new Dictionary<string, string>();
using (StreamReader sw = new StreamReader(fileStream))
{
string rez = "";
while(sw.Peek() > 0)
{
rez = sw.ReadLine();
Console.WriteLine(rez);
string[] words = rez.Split(' ');
line.Add(rez, rez);
}
}
}
}
static void Group(FileStream fileStream, string path)
{
var list = File
.ReadLines(path)
.Select((v, i) => new { Index = i, Value = v })
.GroupBy(p => p.Index / 2)
.ToDictionary(g => g.First().Value, g => g.Last().Value);
}
static void Menu(FileStream fileStream, string path)
{
char choice;
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Welcome this is a English dictionary press d to continue");
Console.ResetColor();
choice = Convert.ToChar(Console.ReadLine());
while (choice == 'd' || choice == 'D')
{
ReadStream2(fileStream, path);
}
}
static void askWord()
{
string ask;
Console.WriteLine("What english word would you like to translate");
ask = Console.ReadLine();
if (ask == )
}
}
}
I have difficulties to understand.
Are you trying to read the words array? words[0] and words[1]?
string[] words = rez.Split(' ');
line.Add(words[0], words[1]);
#Larrythelobster
I write an sample project, hope I can help you:
using System.Text;
class Program
{
static void Main(string[] args)
{
WelcomeText();
string path = "Dictionary.txt";
var dict = ReadFile(path);
var input = GetInputWord();
var translateWord = SearchWord(dict, input);
ShowResult(translateWord);
}
private static void WelcomeText()
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Welcome! This is a English dictionary...");
Console.ResetColor();
}
private static IDictionary<string, string> ReadFile(string path)
{
var lines = File.ReadAllLines(path);
var dict = new Dictionary<string, string>();
foreach(var line in lines)
{
var words = line.Split(' ');
dict.Add(words[0], words[1]);
}
return dict;
}
private static string GetInputWord()
{
Console.WriteLine("Enter a word to translate: ");
var word = Console.ReadLine();
return word;
}
private static string SearchWord(IDictionary<string, string> dict, string wordToSearch)
{
return dict[wordToSearch];
}
private static void ShowResult(string translateWord)
{
Console.WriteLine("The translate word is: " + translateWord);
}
}
Dictionary.txt (English > French):
yellow jaune
red rouge
blue bleu
green vert

How can I replace the string saved on the file

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.

c# value not being stored into accessor

I have 4 class files Driver class (contains main method)
UserInput class (contains GenerateLines & TxtLoadFile methods)
FileHandling.class(contains LoadFile & LoadingFile methods)
Crypting class (empty class at the moment)
My issue is I am trying to get the user to choose which directory out of three to choose a file from. Once chosen I want them to input the file name (.txt) and when that is done I want that value stored and taken to FileHandling class and the LoadFile accessor stores the value into 'TxtFile' variable. I then want to use 'TxtFile' in the method LoadingFile to load the file.
Issue is the value gets stored while in UserInput class but when I call: LoadingFile method in the Driver class it drops the value.
Bear in mind I am student still learning C#, so may not be the best constructed programs as I am just practicing for assignment.
EDIT: I forgot to mention I did check this through debugger but I could not work out how to fix it
Driver class :
namespace UniAssignVigereneCipher
{
class Driver
{
static void Main(string[] args)
{
UserInput UI = new UserInput();
Crypting CR = new Crypting();
FileHandling FH = new FileHandling();
Console.WriteLine(UI.test);
Console.WriteLine(UI.test2);
FH.LoadingFile();
}
}
}
UserInput class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace UniAssignVigereneCipher
{
class UserInput
{
public string test = GenerateLines();
public string test2 = TxtLoadFile();
public static string GenerateLines()
{
string input;
Console.WriteLine("Would you like to encrypt/decrypt a .txt(t) file or a piece text string(s)?\r\nPlease type (t) or (s)");
input = Console.ReadLine();
switch (input)
{
case "t":
case "T":
Console.WriteLine("You have selected a txt file.");
break;
case "s":
case "S":
Console.WriteLine("You have selected to input your own text string.");
break;
default:
break;
}
return input;
}
public static string TxtLoadFile()
{
FileHandling Location = new FileHandling();
int n;
string FileInput;
string TxtFileLoc;
Console.WriteLine("Please choose the location of the .txt file you would like to load from.\r\n1 (Current Location): {0} \r\n2 (Desktop): {1} \r\n3 (My Documents): {2}", Location.CurrentDir, Location.DesktopPath,Location.DocumentsPath);
FileInput = Console.ReadLine();
bool test = int.TryParse(FileInput, out n);
switch (n)
{
case 1:
Console.WriteLine("File Location: {0} \r\nName of file to load: ", Location.CurrentDir);
TxtFileLoc = Console.ReadLine();
Location.LoadFile = Location.DesktopPath + "\\" + TxtFileLoc;
break;
case 2:
Console.WriteLine("File Location: {0} \r\nName of file to load: ", Location.DesktopPath);
TxtFileLoc = Console.ReadLine();
Location.LoadFile = Location.DesktopPath + "\\" + TxtFileLoc;
break;
case 3:
Console.WriteLine("File Location: {0} \r\nPName of file to load: ", Location.DocumentsPath);
TxtFileLoc = Console.ReadLine();
Location.LoadFile = Location.DocumentsPath + "\\" + TxtFileLoc;
break;
default:
break;
}
return FileInput;
}
}
}
FileHandling class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace UniAssignVigereneCipher
{
class FileHandling
{
public string DesktopPath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
public string DocumentsPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
public string CurrentDir = Environment.CurrentDirectory;
string TxtFile;
public string LoadFile
{
get
{
return TxtFile;
}
set
{
TxtFile = value;
}
}
public void LoadingFile()
{
Console.WriteLine("name:" + TxtFile);
StreamReader LF = new StreamReader(TxtFile);
string FileContent = LF.ReadLine();
Console.WriteLine(FileContent);
}
}
}
Try:
static void Main(string[] args)
{
UserInput UI = new UserInput();
Crypting CR = new Crypting();
FileHandling FH = new FileHandling();
Console.WriteLine(UI.test);
Console.WriteLine(UI.test2);
FH.LoadFile = UI.test2;
FH.LoadingFile();
}
Note: It's very odd to put your worker methods into the class construction. it would probably be better to call them like this:
UserInput UI = new UserInput();
string textFile = UI.TxtLoadFile();
//... later on...
FH.LoadFile = textFile;

Seek Method fails to read the text file C#

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();
}

How to give a file path in code instead of command line

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";

Categories