String Array to text document and read it - c#

I'm having issues with with making a program.
I need to make it so it checks whether a text file exists or not, if it exists it displays the contents, if not it prompts the user to enter 5 names, these names are stored into an array are then sent to the text document. I've already tried to do it but I'm getting an error.
Note:
I need to do the names in an array.
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading;
using System.Text.RegularExpressions;
namespace Array
{
class Program
{
public static string line;
public const string file = #"D:\information.txt";
public static string names = #"D:\names.txt";
public static StreamReader myFile = new StreamReader(names);
public static string[] namesArray = new string[4];
public static bool checkFileExists(string names)
{
bool b = false;
if (File.Exists(names))
{
b = true;
}
return b;
}
static void reset() //void used to reset the program
{
Console.ForegroundColor = ConsoleColor.Red;
Console.Write("\nIf there is an error, press Enter to restart");
Console.ForegroundColor = ConsoleColor.White; //changes the text colour of the next line of code to white, better visuals
Console.ReadLine(); //the readkey used to read for any keys being pressed for restarting
Console.Clear(); //clears the console and resets it back to normal
}
static void toFile()
{
Console.ForegroundColor = ConsoleColor.White;
string[] namesArray = new string[5];
Random RandString = new Random();
StreamWriter info = new StreamWriter(file);
for (int x = 0; x < namesArray.Length; x++)
{
Console.Write("Enter a name of class member: {0}", namesArray[x]);
namesArray[x] = Console.ReadLine();
}
for (int x = 0; x < namesArray.Length; x++)
{
info.WriteLine("{0}", namesArray[x]);
}
info.Close();
}
static void Main(string[] args)
{
Console.Title = "Class names to array";
try
{
if (checkFileExists(names))
{
Console.WriteLine("file exists, the contents of the file is: ");
while (myFile1.EndOfStream == false)
{
line = myFile1.ReadLine();
Console.WriteLine(line);
}
Console.ReadLine();
}
else
{
toFile();
}
}
catch (Exception e)
{
Console.WriteLine("Exception: " + e.Message);
}
}
}
The error I'm getting is 'The type initializer for 'Array.Program' threw an exception' and it just closes down.
I've also been told by a friend that my code is really messy, I'm not sure what I need to do to make it better but any help is appreciated.

As #cdhowie said, you will find the details in InnerException. I did notice that your code was a little bit strung out, and admittedly messy, so I decided to write a little sample that does what you want it to in way fewer lines. Many times when doing simple file operations, you can avoid using StreamReader or StreamWriter and instead just use the File class.
Here is the code sample:
using System;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string file = #"D:\information.txt";
if (File.Exists(file))
foreach(var s in File.ReadAllLines(file))
Console.WriteLine(s);
else
{
string[] src = new string[5];
Console.WriteLine("Please enter 5 names:");
for (int i = 0; i < 5; i++)
src[i] = Console.ReadLine();
File.Create(file).Close();
File.WriteAllLines(file, src)
}
}
}
}

Check the details of the "inner exception" in a debugger. You should see that the problem is this line:
public static StreamReader myFile = new StreamReader(names);
This is the only line that could be causing this problem, and likely occurs because the filename contained by the names field doesn't exist, or you don't have access to it (permissions or sharing violation, for example). Correct the problem indicated by the inner exception to make the exception stop happening.
Note that if you did this assignment in the Main() method that the real error would not be masked by the TypeInitializationException, which is thrown whenever a static constructor throws an exception.

Related

Keep getting 'Type cannot be implicitly converted from void to string' [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
So I'm trying to write a program for college. The intended purpose is it is supposed to take students surname and test score and write them to a text file. I keep getting this error. I don't know what to do. The code isn't finished yet I still need to write the other functions for it hence the empty spaces.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace Assignment2
{
class Program
{
static void Main(string[] args)
{
string path = "StudentTestScores.txt";
StreamWriter SW = File.CreateText(path);
string sUsrOpt = "";
byte bNumStudents = 0;
Console.Write("Enter Amount Of Students In The Class (Max 20): ");
byte.TryParse(Console.ReadLine(), out bNumStudents);
string[] sSurnames = new string[bNumStudents];
float[] fScores = new float[bNumStudents];
mainMenu(sUsrOpt, sSurnames, fScores, ref bNumStudents, SW);
Console.WriteLine("Press Any Key To Open File...");
string temp = "";
if (File.Exists(path))
{
using (StreamWriter sr = File.AppendText(path))
for (int i = 0; i < bNumStudents; i++)
{
foreach (var line in (path))
{
Console.WriteLine("");
temp = sr.WriteLine();
Console.Write("Surname: {0}", temp);
Console.WriteLine("");
temp = sr.WriteLine();
Console.Write("Score");
Console.WriteLine("");
}
Console.WriteLine("press any key to continue");
Console.ReadKey();
Console.Clear();
}
}
Console.ReadKey();
System.Diagnostics.Process.Start(path);
SW.Close();
}
//The menu
private static void mainMenu(string sUsrOpt, string[] sSurnames, float[] fScores, ref byte bNumStudents, StreamWriter SW)
{
Console.WriteLine("\nOption A - Open and display a test\nOption B - Enter and save a test\nOption C - Help\nOption D - Exit");
Console.Write("Choose An Option: ");
sUsrOpt = Console.ReadLine();
switch (sUsrOpt.ToUpper())
{
case "A":
Opentests(sSurnames, SW);
break;
case "B":
EnterAndSaveaTest(fScores, sSurnames, ref bNumStudents);
break;
case "C":
Help(fScores, sSurnames, SW);
break;
case "D":
Exit();
break;
default:
break;
}
}
//Enter and save a test
private static void EnterAndSaveaTest(float[] fScores, string[] sSurnames, ref byte bNumStudents)
{
if (bNumStudents > 20)
{
Console.WriteLine("Too High, try again");
}
for (int i = 0; i < bNumStudents; i++)
{
Console.Write("Enter Surname {0}: ", i + 1);
sSurnames[i] = Console.ReadLine();
Console.Write("Enter Score For {0}: ", sSurnames[i]);
float.TryParse(Console.ReadLine(), out fScores[i]);
}
for (int y = 0; y < bNumStudents; y++)
{
Console.WriteLine(fScores[y]);
}
}
//Open a test
private static void Opentests(string[] sSurnames, StreamWriter SW)
{
Console.WriteLine("Please input a previously entered surname");
}
//Gives help to the user
private static void Help(float[] fScores, string[] sSurnames, StreamWriter SW)
{
}
//Ends the program
private static void Exit()
{
Console.ReadLine();
}
}
}
path is a string, you need to open the file (I would use a StreamReader)
then read each line from the StreamReader
foreach (var line in (path))
Then it looks like you are trying to read from a writer
temp = sr.WriteLine();
WriteLine is a void return, you can't assign something with no return to a value.

Avoid writing of equal existing line to text document

I’m new with C# need your help
In this code, I write a some word or phrase to text document with cycle loop. My question is how to avoid writing of equal line, which is already exist in text document and find it in text document, show on output?
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace program_1
{
class Program
{
static void Main(string[] args)
{
int i = 0;
for (;;)
{
Console.Write("Write phrase: ");
var row = Console.ReadLine();
Console.WriteLine(i++ + ". " + (row));
TextWriter tsw = new StreamWriter("lines.txt", true);
tsw.WriteLine(row);
tsw.Close();
}
Console.Read();
}
}
}
If you want to avoid writing duplicate lines in your file, you need a different approach. First, you need to have all of your lines in memory, then check if the user inputs a line already in memory, then write everything at the end of the program
class Program
{
static void Main(string[] args)
{
int i = 0;
List<string> wordsTyped = new List<string>();
// If the file already exists then you can load its content
// in memory to start your checks against the current content
// of the file....
if(File.Exists("lines.txt"))
wordsTyped.AddRange(File.ReadAllLines("lines.txt"));
for (;;)
{
Console.Write("Write phrase: (type 'exit' to end)");
string row = Console.ReadLine();
// Provide a way to exit from this infinite loop
if(row == "exit")
break;
Console.WriteLine(i++ + ". " + (row));
// Use IndexOf to find if there is a match for your row
// and in which position in the List<string>
int position = wordsTyped.IndexOf(row);
if (position != -1)
Console.WriteLine($"Already inserted. Found match at line {position+1} , type again");
else
{
wordsTyped.Add(row);
// It of uttermost importance to enclose the StreamWriter
// in a using statement to be sure to close and dispose it
// after the write, otherwise you could lock yourself out
using(StreamWriter sw = File.AppendText("lines.txt"))
sw.WriteLine(row);
}
}
// File.WriteAllLines("lines.txt", wordsTyped.ToArray());
Console.Read();
}
}

C# Console.ReadKey 1 character lag?

I'm attempting to work with the Console.ReadKey() function in order to intercept the user's keystrokes and rebuild what they are typing on the screen (as I'll need to clear the screen often, move the cursor often, and this seemed like the most full-proof method of making sure what they typed didn't vanish or appear at random points all over the screen.
My question is: Has anyone else ever experienced a 1 character "lag", for lack of a better term, when doing something similar? Say I want to type the word "This". When I press "T", nothing shows up, no matter how long I wait. When I press "h", the "T" appears. "i", the "h" appears. The letter I type will not appear until I hit another key, even if that key is the space bar. Does anyone have any suggestions for what I am doing wrong? I'm sure it has to do with how I am using Console.Readkey, I just don't see what alternative would work. I have attached a small and simple example of this below.
Thank you!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace ConsoleApplication2
{
class Program
{
private static string userInput = "";
static ConsoleKeyInfo inf;
static StringBuilder input = new StringBuilder();
static void Main(string[] args)
{
Thread tickThread = new Thread(new ThreadStart(DrawScreen));
Thread userThread = new Thread(new ThreadStart(UserEventHandler));
tickThread.Start();
Thread.Sleep(1);
userThread.Start();
Thread.Sleep(20000);
tickThread.Abort();
userThread.Abort();
}
private static void DrawScreen()
{
while (true)
{
Console.Clear();
Console.SetCursorPosition(0, 0);
Console.Write("> " + userInput);
Thread.Sleep(300);
}
}
private static void UserEventHandler()
{
inf = Console.ReadKey(true);
while (true)
{
if (inf.Key != ConsoleKey.Enter)
input.Append(inf.KeyChar);
else
{
input = new StringBuilder();
userInput = "";
}
inf = Console.ReadKey(true);
userInput = input.ToString();
}
}
}
}
It is because you have 2 times Console.ReadKey()
If you change your code into this
private static void UserEventHandler()
{
while (true)
{
inf = Console.ReadKey(true);
if (inf.Key != ConsoleKey.Enter)
input.Append(inf.KeyChar);
else
{
input = new StringBuilder();
userInput = "";
}
userInput = input.ToString();
}
}
It does not lag. the second Console.ReadKey() is blocking in your code. I did not check if you need the parameter true to the readkey, that's for you to find out

Text file only reading odd OR even lines?

I'm trying to write a little C# program that reads from a text file and lets you choose a line to print out.
For some reason, it will only print lines 1,3,5,etc.
If I change the bit that says int chooseLine = Convert.ToInt32(input); to int chooseLine = (int)Convert.ToInt64(input);, then it only prints even lines.(0,2,4,6,etc).
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
class Steve
{
public static int count = 0;
public static String[] steveTalk;
public static void Main()
{
using (StreamReader r = new StreamReader("Steve.txt"))
{
string line;
while ((line = r.ReadLine()) != null)
{
count++;
}
}
using (StreamReader sr = new StreamReader("Steve.txt"))
{
int i = 0;
steveTalk = new String[count];
String line;
while ((line = sr.ReadLine()) != null)
{
steveTalk[i] = line;
Console.WriteLine(steveTalk[i]);
i++;
}
}
while (true)
{
string input = Console.ReadLine();
int chooseLine = Convert.ToInt32(input);
try
{
Console.WriteLine(steveTalk[chooseLine]);
}
catch
{
Console.WriteLine("Error! Not a number or array index out of bounds");
}
Console.ReadLine();
}
}
}
Any ideas?
I'd like to suggest the System.IO.File.ReadAllLines(filename) method.
string []lines=System.IO.File.ReadAllLines("Steve.txt");
string input ;
while ((input = Console.ReadLine()) != "end")
{
int chooseLine;
int.TryParse(input,out chooseLine);
if(chooseLine<lines.Length)
{
Console.WriteLine(lines[chooseLine]);
}
}
There is no such problem with your code. What you might experience is that you have a Console.ReadLine() at the end of your loop, so if you enter a number it will show that line, then enter another number, that number will be ignored. Every other number that you enter will be ignored, which fits your description if you only tried to enter the numbers in sequence.
Here is some improvements to the code.
Use File.ReadAlLines to read the file.
Don't use exceptions unless you need it. You can easily check the input before any exception occurs.
Code:
using System;
using System.IO;
class Steve {
public static void Main() {
string[] lines = File.ReadAllLines("Steve.txt");
while (true) {
int line;
if (Int32.TryParse(Console.ReadLine(), out line)) {
if (line >= 0 && line < lines.Length) {
Console.WriteLine(lines[chooseLine]);
} else {
Console.WriteLine("Error! Array index out of bounds");
}
} else {
Console.WriteLine("Error! Not a number");
}
}
}
}

C# first element of string is missing

I wrote a program, what is compute the difference of two string or compute a hamming distance.
I run in debug mode. And I saw, the at the string first the first element of string is missing. But the string second is good!
When I tested the first's length and second's length is equal.
Forexample:
I typed this: 00011
And in debug mode it's value only: 0011
. Or I typed this: "this", in debug the real value is only "his"
Somebody can explain me, why missing the first element of string?
The code:
while (Console.Read() != 'X')
{
string first = Console.ReadLine();
string second = Console.ReadLine();
int distance = 0;
for (int i = 0; i < first.Length; i++)
{
if (first[i]!= second[i])
{
++distance;
}
}
Console.WriteLine("Hamming distance is {0}.", distance);
}
I tried modify the iteration, forexample the loop was ++i, or the first[i-1] but these aren't solve my problem.
Console.Read() reads the first character from the buffer. This character will not be included in the ReadLine().
I would personally find a better way to end your program such as if first=="quit" or by some other syntaxic means.
You consume the first char with Console.Read() so it will not appear in first:
string first = Console.ReadLine();
while ((first != null) && (first[0] != 'X'))
{
string second = Console.ReadLine();
int distance = 0;
for (int i = 0; i < first.Length; i++)
{
if (first[i]!= second[i])
{
++distance;
}
}
Console.WriteLine("Hamming distance is {0}.", distance);
first = Console.ReadLine();
}
I have the same problem in vb.net and found out that it was causing by "console.readkey()". console should only read one at time.See you have multiple read function at same time.
like Readkey() at main() and readline() on Background.thread...
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace_File_Handling
{
class Program
{
static void Main(string[] args)
{
string path = #"E:\File.txt";
StreamReader r1 = new StreamReader(path);
string m = r1.ReadToEnd();
Console.WriteLine(m);
Console.ReadKey();
r1.Close();
StreamWriter wr = File.AppendText(path);
string na = Convert.ToString(Console.ReadLine());
wr.WriteLine(na);
wr.Close();
Console.WriteLine(na);
Console.ReadKey();
StreamReader rd = new StreamReader(path);
string val = rd.ReadToEnd();
Console.WriteLine(val);
rd.Close();
Console.ReadKey();
}
}
}

Categories