I'm trying to save array of strings to a txt file - c#

I'm designing a program to save food recipes. The problem is when I save the ingredients of a new recipe it deletes the ingredients of the old recipe. I want both of them to be saved. Here's the code I use:
Console.WriteLine("Enter the path where your files will be saved: ");
string fileName = Console.ReadLine();
Console.WriteLine("Please enter the main ingrediant for your recipe: ");
string Main = Console.ReadLine();
Console.WriteLine("Please enter how many ingrediants in your recipe: ");
int Ingrediants = Convert.ToInt32(Console.ReadLine());
string[] a = new string[Ingrediants];
Recpies recipe1 = new Recpies(Main, Ingrediants);
recipe1.Ingrediants = new List<string[]>();
recipe1.TheMainIngrediant = Main;
Console.WriteLine("Please enter your ingrediants: ");
for (int i = 0; i < Ingrediants; i++)
{
a[i] = Console.ReadLine();
}
using (var file = System.IO.File.OpenText(fileName))
{
string line;
while ((line = file.ReadLine()?.Trim()) != null)
{
// skip empty lines
if (line == string.Empty)
{
recipe1.Ingrediants.Add(a);
recipe1.Saving(fileName, Ingrediants, a);
}
else
{
continue;
}
}
}

One possible way to achieve what you want is to use a combination between StreamWriter and File.AppendText, this is not going to overwrite the text you already save on that file instead of that is going to append the info at the end of the file (this example might be helpful: Append Text). Hope this helps! šŸ‘

Just add true as second parameter
TextWriter tsw = new StreamWriter(fileName, true);

Related

Adding multiple rows to a table in docx files with OpenXML

I am using TemplateEngine.Docx, Template engine for generating Word docx in Visual Studio for C#. Basically I am trying to add multiple rows to a table in an edited word document using a for loop. However when I loop through the if statement it will just rewrite the data that was just read. Here is my code:
if (fieldName == "examrubric")
{
for (; ; )
{
Console.WriteLine("To enter a row to the tabel type 'yes'\n");
string choice = Console.ReadLine();
if (choice == "yes")
{
Console.WriteLine("Enter a value for the question number:\n");
string qnum = Console.ReadLine();
Console.WriteLine("Enter a value for what the question is out of:\n");
string score = Console.ReadLine();
Console.WriteLine("Enter a value for how much was scored:\n");
string qscore = Console.ReadLine();
Console.WriteLine("Enter a value for score:\n");
string score2 = Console.ReadLine();
Console.WriteLine("Enter the total mark:\n");
string total = Console.ReadLine();
valuesToFill = new Content(
new TableContent("examrubric")
.AddRow(
new FieldContent("qnum", qnum),
new FieldContent("score", score),
new FieldContent("qscore", qscore),
new FieldContent("score2", score2),
new FieldContent("total", total)));
}
else
{
break;
}
}
}
You could try the following code to write data to the docx file in the loop to avoid the rewrite the data .
static void Main(string[] args)
{
File.Copy("test1.docx", "OutputDocument.docx");
Console.WriteLine("To enter a row to the tabel type 'yes'\n");
string choice = Console.ReadLine();
Content valuesToFill = new Content(new TableContent("Team Members Table"));
for (int i = 0; i < 2; i++)
{
if (choice == "yes")
{
Console.WriteLine("Enter a value for the Name:\n");
string name = Console.ReadLine();
Console.WriteLine("Enter a value for the Role:\n");
string role = Console.ReadLine();
valuesToFill.Tables.First().AddRow(
new FieldContent("Name", name),
new FieldContent("Role", role)) ;
}
}
using (var outputDocument = new TemplateProcessor("OutputDocument.docx").SetRemoveContentControls(true))
{
outputDocument.FillContent(valuesToFill);
outputDocument.SaveChanges();
}
}
Tested result:

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", ",");
}

How to display a string

I am working on a small code that searches an input text file (of my choice). I am creating a search function. So far I got it to display how many times the search word occurs in the text file and also the line number. I need some help on displaying how the searched word appears in the text file. For example, If I search for the word "the" and it appears as "THE" or "The" in the text file, I would want to display that on my console window.
Any help, advice, or suggestion is appreciated. Thank you in advance!
Here is my code:
string line;
int counter = 0;
Console.WriteLine("Enter a word to search for: ");
string userText = Console.ReadLine();
string file = "NewTextFile.txt";
StreamReader myFile = new StreamReader(file);
int found = 0;
while ((line = myFile.ReadLine()) != null)
{
counter++;
if (line.Contains(userText))
{
Console.WriteLine("Found on line number: {0}", counter);
found++;
}
}
Console.WriteLine("A total of {0} occurences found", found);
You can use IndexOf instead of Contains since you want to do case-insensitive search:
if (line.IndexOf(userText, StringComparison.CurrentCultureIgnoreCase) != -1)
{
Console.WriteLine("Found on line number: {0}", counter);
found++;
}
This might do the trick for you
While ((line = myFile.ReadLine()) != null)
{
line = line.toUpper();
counter++;
if (line.Contains(userText.toUpper()))
{
Console.WriteLine("Found on line number: {0}", counter);
Console.WriteLine(line.SubString(line.IndexOf(userText),userText.Length));
found++;
}
}
Console.WriteLine("A total of {0} occurences found", found);
The line which is added here is
line.SubString(line.IndexOf(userText),userText.Length)
It means we need to find a SubString inside the line starting from the index of the first occurence of userText and the till the length of userText length
and if you wanted to only compare the string and show the original string you can use this code
While ((line = myFile.ReadLine()) != null)
{
string linecmp = line.toUpper();
counter++;
if (linecmp.Contains(userText.toUpper()))
{
Console.WriteLine("Found on line number: {0}", counter);
Console.WriteLine(line.SubString(line.IndexOf(userText),userText.Length));
found++;
}
}
Console.WriteLine("A total of {0} occurences found", found);
I have slightly modified your search function to resolve the issue you had before. As you mentioned in the comment, you said it is matching word 'THEIR' with word 'THE'.
Add the following code to resolve the mismatches issue.
string userText = Console.ReadLine() + " ";
Modified Full code below.
string line;
int counter = 0;
Console.WriteLine("Enter a word to search for: ");
string userText = Console.ReadLine() + " ";
string file = "NewTextFile.txt";
StreamReader myFile = new StreamReader(file);
int found = 0;
while((line = myFile.ReadLine()) != null)
{
line = line.ToUpper();
counter++;
if (line.Contains(userText.ToUpper()))
{
Console.WriteLine("Found on line number: {0}", counter);
Console.WriteLine(line.Substring(line.IndexOf(userText)+1,userText.Length));
found++;
}
}
Console.WriteLine("A total of {0} occurences found", found);
Console.ReadLine();
Hope this helps you.

How can I edit numbers in my .txt file?

I have code here and based on user input, I'd like to change the line of choice I will have selected. However, I can only currently temporarily change the line of text and when I write out the file again, the text had not overwritten permanently.
Here's my code:
public struct classMates
{
public string first;
public string last;
public int ID;
}
static classMates[] readClassMates(classMates[] classMateInfo)
{
StreamReader sr = new StreamReader(#"C:\class.txt");
int count = 0;
while (!sr.EndOfStream)
{
classMateInfo[count].first = sr.ReadLine();
classMateInfo[count].last = sr.ReadLine();
string idTemp = sr.ReadLine();
classMateInfo[count].ID = Convert.ToInt32(idTemp);
count++;
}
sr.Close();
return classMateInfo;
}
static void editClassMates(classMates[] classMateInfo)
{
Console.Write("Who's number would you like to change? ");
string classMateInput = Console.ReadLine();
for (int i = 0; i < classMateInfo.Length; i++)
{
if (classMateInfo[i].first.Equals(classMateInput))
{
Console.Write("Enter new number: ");
string temp = Console.ReadLine();
int classMateNumber = Convert.ToInt32(temp);
classMateInfo[i].ID = classMateNumber;
Console.WriteLine("You have successfully changed {0}'s number to {1}.", classMateInfo[i].first,classMateInfo[i].ID.ToString());
}
}
}
static void Main()
{
classMates[] classMateInfo = new classMates[43];
listClassMates(classMateInfo);
editClassMates(classMateInfo);
listClassMates(classMateInfo);
}
I know I am meant to use File.WriteAllText(), but I don't know how to utilize this snippet into my code.
Maybe you're expecting an easy answer but you actually require custom code that you need to think up yourself.
If you're into LINQ and really want to use the File.WriteAllText() method you can use this oneliner i wrote for you, which I haven't tested:
File.WriteAllText(#"C:\class.txt", string.Join(Environment.NewLine, (from cm in classMateInfo select string.Format("{1}{0}{2}{0}{3}", Environment.NewLine, cm.first, cm.last, cm.ID)).ToArray()));
Which creates a string array from your classMateInfo, concatenates the array using a newline as separator and write the entire string to the specified file.
I donĀ“t see you writing anything to a file.
Console.Write("Enter new number: ");
string temp = Console.ReadLine();
int classMateNumber = Convert.ToInt32(temp);
classMateInfo[i].ID = classMateNumber;
Console.WriteLine("You have successfully changed {0}'s number to {1}.", classMateInfo[i].first,classMateInfo[i].ID.ToString());
I should expect that you did something like:
rs.Writeline('foo');
But perhaps you need a streamwriter for that.

C# measurement conversion with StreamReader only reading only 1 line from file [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Okay so I'm working on a project for the conversion of measurements using StreamReader to read a file with the following list of conversions:
ounce,gram,28.0
pound,ounce,16.0
pound,Kilogram,0.454
pint,litre,0.568
inch, centimetre,2.5
mile,inch,63360.0
When the program runs it will ask the the user to input the amount they want to convert followed by the measurement the want to convert, followed by the measurement they want to convert it into. So e.g. 5,ounce,gram
After getting the input the program would look at the file and calculate the conversion rate so 5 ounces = 140 grams so the program would display as a end result
"5 ounce equals 140 gram"
The problem I'm getting with this program is the fact that the StreamReader is only reading the first line of the convert.txt file, for example if I was to put 2,pound,ounce it would return back the text for the first line followed by a message "Not Matched" so the it would look something like this:
Please input the amount, to and from type (Ex.5,ounces,grams):
2,pound,ounce
ounce,gram,28.0
Not Matched
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace Soft140AssPt3V2
{
class Program
{
static void Main(string[] args)
{
string line, programStart, programEnd, j, l, lineTotal = "";//linetotal to take all lines from the file
double factor, endResult, amount;
string[] SplitData = new string[2];
string[] fileLines;
StreamReader unitsOfMeasurement = new StreamReader("../../convert.txt"); //Reads the convert.txt file
Console.WriteLine("convert.txt has uploaded");
while ((line = unitsOfMeasurement.ReadLine()) != null)
{
lineTotal += line + "\n";
}
fileLines = lineTotal.Split('\n');//place file lines in an array of string
//Get inputs
Console.WriteLine("\nPlease input the amount, to and from type (Ex. 5,ounces,grams):");
string userInput = Console.ReadLine();
for (int i = 0; i < fileLines.Length - 1; i++)
{
Console.WriteLine(fileLines[i]);
SplitData = fileLines[i].Split(',');
programStart = SplitData[0];
programEnd = SplitData[1];
factor = Convert.ToDouble(SplitData[2]);
string[] filter = userInput.Split(',', ' ', '/', '.');
amount = Convert.ToDouble(filter[0]);
j = filter[1];
l = filter[2];
if (j == programStart)
{
endResult = (factor * amount);
Console.WriteLine("\n{0} {1} equals {2} {3}", amount, filter[1], endResult, filter[2]);
Console.ReadLine();
}
else
{
Console.WriteLine("Not Matched");
Console.ReadLine();
}
}
unitsOfMeasurement.Close();
}
}
}
Solution 1:
StringBuilder lineTotal = new StringBuilder();
while ((line = unitsOfMeasurement.ReadLine()) != null)
{
lineTotal.Append(line + Environment.NewLine);
}
fileLines = lineTotal.ToString().Split(new string[]{Environment.NewLine},
StringSplitOptions.RemoveEmptyEntries);
Solution 2:
StringBuilder lineTotal = new StringBuilder();
foreach(var line in File.ReadLines("../../convert.txt"))
{
lineTotal.Append(line);
}
fileLines = lineTotal.ToString().Split(new string[]{Environment.NewLine},
StringSplitOptions.RemoveEmptyEntries);
Solution 3:
string fileName = "../../convert.txt";
var lines = File.ReadLines(fileName).Where(line =>
!string.IsNullOrWhiteSpace(line)).ToArray();
Here is the optimized Code (You can further modify it as per your requirement):
static void Main(string[] args)
{
try
{
double factor, endResult, amount;
string[] fileLines;
StreamReader unitsOfMeasurement = new StreamReader("../../convert.txt"); //Reads the convert.txt file
Console.WriteLine("convert.txt has uploaded");
fileLines = unitsOfMeasurement.ReadToEnd().Replace("\r\n", "\n").Split('\n');//place file lines in an array of string
//Get inputs
Console.WriteLine("\nPlease input the amount, to and from type (Ex. 5,ounce,gram):");
string userInput = Console.ReadLine();
bool blnFound = false;
for (int i = 0; i < fileLines.Length; i++)
{
string[] filter = userInput.Split(',');
if ((filter.Length == 3) && (filter[1].Trim() == fileLines[i].Split(',')[0].Trim()))
{
blnFound = true;
Console.WriteLine(fileLines[i]);
factor = Convert.ToDouble(fileLines[i].Split(',')[2]);
amount = Convert.ToDouble(filter[0]);
endResult = (factor * amount);
Console.WriteLine("\n{0} {1} equals {2} {3}", amount, filter[1], endResult, filter[2]);
Console.ReadLine();
break;
}
}
if (blnFound == false)
{
Console.WriteLine("Not Matched");
Console.ReadLine();
}
unitsOfMeasurement.Close();
}
catch (Exception ex)
{
throw (ex);
}
}

Categories