Remove Empty lines from file c# - c#

Ok I tried several codes. I just can't figure out what to do here..
I am doing a quiz. I save the questions and answers like that.
private void btnsave_Click(object sender, EventArgs e)
{
//checking if question or answer textbox are empty. If they are not then the question is saved
if (txtquestion.Text != "" & txtanswer.Text != "")
{
//saves the question in the questions text
using (System.IO.StreamWriter file = new System.IO.StreamWriter(#"C:\Users\User\Desktop\Assignment 2 Solo part\Questions.txt", true))
{
file.WriteLine(txtquestion.Text);
}
//saves the answer in the answers text
using (System.IO.StreamWriter file = new System.IO.StreamWriter(#"C:\Users\User\Desktop\Assignment 2 Solo part\Answers.txt", true))
{
file.WriteLine(txtanswer.Text);
}
MessageBox.Show("Question and Answer has been succesfully added in the Quiz!", "Success!", MessageBoxButtons.OK, MessageBoxIcon.None);
//cleaning the textboxes for a new question and answer
txtanswer.Text = "";
txtquestion.Text = "";
}
//checks if the question textbox is empty and shows the corresponding message
else if (txtquestion.Text == "")
MessageBox.Show("Please enter a question", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
else //checks if the answer textbox is empty and shows the corresponding message
if (txtanswer.Text == "")
MessageBox.Show("Please enter an answer", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
until here everything is fine. The problem is after I delete a question there are empty lines in the file and I tried lots of stuff. I changed 2 times the way i save them. still I can make it work. Now I am also getting an out of bounds error when i delete a question because of the empty spaces that are created.
Here is the delete code:
private void fmrdelete_Load(object sender, EventArgs e)
{//declaration
int i=0;
//loading values to array from file
string[] qlines = System.IO.File.ReadAllLines(#"C:\Users\User\Desktop\Assignment 2 Solo part\Questions.txt").ToArray();
foreach (string line in qlines)
{
Console.WriteLine(line);
//saving each line to array possition
questions[i] = line;
i++;
lstboxquestions.Items.Add(line);
}
i = 0;
//loading values to array from file
string[] alines = System.IO.File.ReadAllLines(#"C:\Users\User\Desktop\Assignment 2 Solo part\Answers.txt").ToArray();
foreach (string line in alines)
{
Console.WriteLine(line);
//saving each line to array possition
answers[i] = line;
i++;
}
}
private void btndelete_Click(object sender, EventArgs e)
{
//declarations
int line_to_delete;
int count;
int i=0;
//changing the value given from textbox to integer and then saving it
line_to_delete = Convert.ToInt32(txtans.Text);
//checking to find the question we want to delete
for (count = 0; count < 20; count++)
{
if (count == (line_to_delete-1))
{
questions[count]= "";
}
}
//clearing file
System.IO.File.WriteAllText(#"C:\Users\User\Desktop\Assignment 2 Solo part\Questions.txt",string.Empty);
//saving to file
for (count = 0; count < 20; count++)
{
//saves the question in the questions text
using (System.IO.StreamWriter file = new System.IO.StreamWriter(#"C:\Users\User\Desktop\Assignment 2 Solo part\Questions.txt", true))
{
file.WriteLine(questions[count]);
}
}
//clearing the listbox
lstboxquestions.Items.Add(" ");
//loading from file back to array
string[] qlines = System.IO.File.ReadAllLines(#"C:\Users\User\Desktop\Assignment 2 Solo part\Questions.txt").ToArray();
foreach (string line in qlines)
{
line.Replace("\n\n", "\n");
Console.WriteLine(line);
//saving each line to array possition
questions[i] = line;
i++;
lstboxquestions.Items.Add(line);
}
//checking to find the answers we want to delete
for (count = 0; count < 20; count++)
{
if (count == (line_to_delete - 1))
{
answers[count] = "";
}
}
//clearing file
System.IO.File.WriteAllText(#"C:\Users\User\Desktop\Assignment 2 Solo part\Answers.txt", string.Empty);
//saving to file
for (count = 0; count < 20; count++)
{
//saves the question in the questions text
using (System.IO.StreamWriter file = new System.IO.StreamWriter(#"C:\Users\User\Desktop\Assignment 2 Solo part\Answers.txt", true))
{
file.WriteLine(answers[count]);
}
}
string[] alines = System.IO.File.ReadAllLines(#"C:\Users\User\Desktop\Assignment 2 Solo part\Answers.txt").ToArray();
foreach (string line in alines)
{
Console.WriteLine(line);
//saving each line to array possition
answers[i] = line;
i++;
}
}
}
So how to remove the empty lines ?

When you delete line and then save to file instead of:
file.WriteLine(questions[count]);
try:
if(!string.IsNullOrWhiteSpac(questions[count]))
file.WriteLine(questions[count]);
Do the same with answers.
EDIT:
Have you tried insted of:
file.WriteLine(answers[count]);
this:
if(!string.IsNullOrWhiteSpac(answers[count]))
file.WriteLine(answers[count]);

Related

Outputting the content of an array to a text file in C#

I need your help.
I want to make a program where I give a number and it increments it as many times as I said and write output into a .txt file. I have an issue with writing it because it only writes one output. I know basics but I have never worked with more complicated coding, only a few games, and simple apps.
int baseNumber = int.Parse(tbBase.Text);
int codeNumber = int.Parse(tbCodeNumber.Text);
int[] codes = new int[codeNumber];
int count = 0;
string link = "https://www.roblox.com/groups/";
for (int i =0; i < codes.Length; i++)
{
codes[i] = baseNumber++;
}
foreach (int element in codes)
{
string text= $"{link}{Convert.ToString(codes[count])}";
System.IO.File.WriteAllText(#"D:\TextFiles\WriteText.txt", text);
count++;
}
you can use this code . You wrote the number of for loops in the file, which is wrong. Put the text in a string and put it in the file
int baseNumber = int.Parse(tbBase.Text);
int codeNumber = int.Parse(tbCodeNumber.Text);
int[] codes = new int[codeNumber];
for (int i = 0; i < codes.Length; i++)
{
codes[i] = baseNumber++;
}
int count = 0;
string text = "";
string link = "https://www.roblox.com/groups/";
foreach (int element in codes)
{
text += $"{link}{Convert.ToString(codes[count])}";
count++;
}
string fileName = #"D:\WriteText.txt";
if (File.Exists(fileName))
System.IO.File.AppendAllText(fileName, text);
else
System.IO.File.WriteAllText(fileName, text);
Read text file for editing
public void ReadFile(string fileName)
{
string[] lines = System.IO.File.ReadAllLines(fileName);
// Display the file contents by using a foreach loop.
string text = "";
foreach (string line in lines)
{
// Use a tab to indent each line of the file.
text += line + Environment.NewLine;
Console.WriteLine("\t" + line);
}
}

Read from file split content into group when empty line

I´m reading a file in my C# code.
The file looks like this:
13
56
89
55
66
9
58
I´m trying to read the file and split the numbers up in different variabels.
Want it look like this:
numb1 = 13,56,89
numb2 = 55,66
numb3 = 9
numb4 = 58
When it is a blank line I want to split it up and group numbers together. But I don´t know how to do.
My code so far:
static void Main(string[] args)
{
InputReader inputReader = new InputReader();
var file =File.ReadAllLines(#"C:\Users\forsb\source\repos\ConsoleApp1\ConsoleApp1\Input\numberlist.txt");
string[] a = new string[] { };
foreach (var item in file)
{
a = item.Split(new string[] { "\r\n\r\n" },
StringSplitOptions.RemoveEmptyEntries);
}
Console.WriteLine();
Console.Read();
}
You can try the below code
public static void Main()
{
var fileName = "filename.txt";
// CREATE a file in your Sandbox using .NET Fiddle
WriteFile(fileName);
string line;
var str="";
// Read the file and display it line by line.
System.IO.StreamReader file =
new System.IO.StreamReader(fileName);
while((line = file.ReadLine()) != null)
{
line = line.Trim();
//if line is empty
//show total values until now
if (line == "")
{
Console.WriteLine(str);
str="";
continue;
}
else
{
//if first element, add here
if(str != "")
{
str=str+","+line;
}
else
{
str=line;
}
}
}
//for remaining last line
Console.WriteLine(str);
file.Close();
}
public static void WriteFile(string path)
{
File.WriteAllText(path, "13\n56\n89\n\n\n\n55\n66\n\n\n\n9\n58");
}
I have used the sample code in fiddle looks working.
https://dotnetfiddle.net/hOFSi2
basically, i am trying to read here line by line, if line is empty and there is some data saved in "str" print it, else continue
Note: You don't need to create file using "WriteFile" function, I have created it in fiddle, so adding code here for reference.
I would create a List<List<int>> to hold your sets of numbers. Then you can do whatever you want with them.
static void Main(string[] args)
{
String fileName = #"C:\Users\forsb\source\repos\ConsoleApp1\ConsoleApp1\Input\numberlist.txt";
List<List<int>> numberSets = new List<List<int>>();
// Read the file and collect the numbers in "curSet" until a blank line is encountered
List<int> curSet = new List<int>();
foreach (String line in System.IO.File.ReadLines(fileName))
{
if (line.Trim().Length == 0)
{
// blank line found, add the current set of numbers to our list,
// but only if the current set actually has any numbers in it.
if (curSet.Count > 0)
{
numberSets.Add(curSet);
curSet = new List<int>();
}
}
else
{
int number;
if (int.TryParse(line, out number))
{
curSet.Add(number);
}
}
}
// end of file reached, add a pending set of numbers if it exists
if (curSet.Count > 0)
{
numberSets.Add(curSet);
}
// do something with the collection of number lists:
for(int i=0; i<numberSets.Count; i++)
{
List<int> numberSet = numberSets[i];
// ... do something with "numberSet" ...
Console.WriteLine(i + ": " + String.Join(",", numberSet));
}
Console.Write("Press Enter to Quit");
Console.ReadLine();
}
Output on my system:
0: 13,56,89
1: 55,66
2: 9
3: 58
Press Enter to Quit
You are doing the split for each row that you read from the file. You need to do the split for the complete content of the file.
Code below will give the output you want.
a[0] = 13,56,89
a[1] = 55,66
a[2] = 9
a[3] = 58
var data = File.ReadAllText(#"C:\Users\forsb\source\repos\ConsoleApp1\ConsoleApp1\Input\numberlist.txt");
string[] a = data.Split("\r\n\r\n", System.StringSplitOptions.RemoveEmptyEntries);
for(int i = 0; i < split.Length; i++)
{
a[i] = a[i].Replace("\r\n", ",");
}

Creating a yearly summary from a filed Array using Stream Writer c#

So I need to create a Yearly Summary that gives feedback from the amount of events held a year. There must be an event held each month for this to happen.
So far I have stored the months in an array like this:
public string[] sMonths = new string[12] { "01", "02", "03", "04", "05",
"06", "07", "08", "09", "10", "11", "12" };
I then initiate the array into a combo box, with a counter:
for (iCount = 0; iCount < sMonths.Length; iCount++)
{
cboMonth.Items.Add(sMonths[iCount]);
}
Then take this information from the interface (windows form) like this:
sEventName = txtEvent.Text;
sVenueName = txtVenue.Text;
lstActivity.Items.Add("Dance");
lstActivity.Items.Add("Theatre");
lstActivity.Items.Add("Music");
}
//summary
private void btnExit_Click(object sender, EventArgs e)
{
DialogResult dialogResult = MessageBox.Show("Are up you sure you want to exit?", "Exit", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (dialogResult == DialogResult.Yes)
{
Application.Exit();
}
}
private void btnAdd_Click(object sender, EventArgs e)
{
using (StreamWriter sw = new StreamWriter("EVENTS.TXT", true))
{
sw.WriteLine(txtEvent.Text);
sw.WriteLine(txtVenue.Text);
sw.WriteLine(cboMonth.SelectedItem.ToString());
sw.WriteLine(lstActivity.SelectedItem);
if (rdoRange1.Checked == true)
{
sw.WriteLine(rdoRange1.Text);
}
else if (rdoRange2.Checked == true)
{
sw.WriteLine(rdoRange2.Text);
}
else if (rdoRange3.Checked == true)
{
sw.WriteLine(rdoRange3.Text);
}
else
{
sw.WriteLine(rdoRange4.Text);
}
sw.Close();
}
}
I'm not sure if I am doing this correctly, or if I am getting my counters confused, or infact need to use more than 1? But when I then try to create the summary, nothing appears at all?
private void btnSummary_Click(object sender, EventArgs e)
{
using (StreamReader sr = new StreamReader("EVENTS.TXT"))
{
for (iCount = 12; iCount < sMonths.Length; iCount++)
{
if (iCount == 12)
{
sMonths[iCount] = sr.ReadLine();
listBox1.Items.Add("You held an event every month of the year.");
}
else
{
label1.Text = " ";
listBox1.Items.Add("You cannot produce a yearly summary until you have entered an event for each month");
}
}
I try to read the information from the file but it's returning nothing at all.
I am trying to get this to work using local variables, before transferring it into classes.
there may be many errors in my code, I am new to this.
Thanks in advance, any advice appreciated.
UPDATE:
a sample of my readfile is:
jdisfhs
ddnsojds
05
Dance
0
There will be 12 records in each of them. I need to check each value against variables and produce the outcome.
There are a few problems with this chunk:
for (iCount = 12; iCount < sMonths.Length; iCount++)
sMonths is an array of 12 elements so sMonths.Length = 12.
You create your counter with the value 12 and your condition to loop is that your counter is strictly inferior to 12, so you will never enter the loop.
To loop through an array you usually want to do something like :
for(int iCount = 0; iCount < sMonths.Length; iCount++)
But in this case you want to read a file, so your loop should be on the file reader with something like that :
private void btnSummary_Click(object sender, EventArgs e)
{
using (StreamReader sr = new StreamReader("EVENTS.TXT"))
{
string line = string.Empty;
/*the condition in the while reads the next line and puts it in line,
then tests if line is null because sr.ReadLine()
returns null when the end of the document is reached*/
while ((line = sr.ReadLine()) != null)
{
//Do your tests on line
}
}
}

How to read from a text file then convert the text into a string then an integer

Ok so im trying to convert text from a text file to a string then to an integer so then I could use them in my array(I know there's simpler ways of stating how big a 2D array is but I just want to do it this way so I can learn).
Map.txt (First line in the text)
20, 20
Then is just a integer map that below.
Here is the code that reads the text and displays also the map, again I want to Take the first line of Map.txt convert it to a string, then to an int so then I could use it for other things
static void worldLoad()
{
int counter = 0; //Why do I need to declare it as 0....
string line;
//Read the file
System.IO.StreamReader file = new System.IO.StreamReader(#"Map.txt");
while((line = file.ReadLine()) != null)
{
Console.WriteLine(line);
counter = counter + 1;
if(counter == 1)
{
Console.Clear();
}
if(counter == 21)
{
break;
}
}
}
No need to convert file.ReadLine() to a string, it's already a string. What you want to do is int.TryParse(). See below:
static void Main(string[] args)
{
int counter = 0;
string line;
int output;
//Read the file
System.IO.StreamReader file = new System.IO.StreamReader(#"Map.txt");
while ((line = file.ReadLine()) != null)
{
int.TryParse(line, out output);
Console.WriteLine(line);
counter = counter + 1;
if (counter == 1)
{
Console.Clear();
}
if (counter == 21)
{
break;
}
}
}

Error Checking file c#

I have a program that opens a .txt file and stores it into an array. If the file contains anything other than one number per line than I get an error and the program crashes. I was wondering if there was a way to prevent this from happening and giving the user a message if their file is invalid.
public void Load_Button_Click(object sender, EventArgs e)
{
this.progressBar1.Value = 0; // Reset progress bar
List<int> list = new List<int>();
OpenFileDialog ofd = new OpenFileDialog(); // Initialize open file dialog
ofd.Filter = "TXT File|*.txt"; // Set acceptable files
ofd.Title = "Open File";
if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
// Open the selected file to read.
string[] lines = File.ReadAllLines(ofd.FileName); // Read all lines in data file selected
dataArray = new int[lines.Length];
for (int i = 0; i < dataArray.Length; ++i)
{
dataArray[i] = int.Parse(lines[i]); // Add data to dataArray array
Unsorted_Box.Text += lines[i] + ", "; // Add data to unsorted box
}// end for
}
}
use int.TryParse():
for (int i = 0; i < dataArray.Length; ++i)
{
if (!int.TryParse(lines[i],out dataArray[i]) // Add data to dataArray array
{
// do something about the invalid data - message / ignore etc..
}
Unsorted_Box.Text += lines[i] + ", "; // Add data to unsorted box
}// end for
Do you know how I would error check this line:
var result2 = text.Split(" \r\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)?.Select(num => double.Parse(num)).OrderBy(d => d).ToArray();"
var result2 = text.Split(" \r\n".ToCharArray(),
StringSplitOptions.RemoveEmptyEntries)?.Select(num =>
{
double result;
if (!double.TryParse(num, out result))
{ // error set result to value other than zero if you need to }
return result;
}).OrderBy(d => d).ToArray();"

Categories