I was wondering, how can i add a new line to a text document. For an instance, I have a text document with numbers or whatever which contains the following two lines of text:
"444444
323233"
And I want to add a new line, in which would like to add new combination of numbers, so how can I do that? I first save all lines in a array, print them and ask the user to choose which line to edit and if the chosen line does not exist (in this situation if the user types the number "3" in the variable n), I want the program to create a new line.
string path = C:\...\text1.text
string[] lines = File.ReadAllLines(path);
int i = 1;
foreach (var line in lines)
{
Console.WriteLine("{0}. {1}", i, line);
i++;
}
Console.Write("Choose which line to edit: ");
int n = int.Parse(Console.ReadLine());
n--;
Console.Write("{0}. ", n + 1);
lines[n] = lines[n].Replace(lines[n], Console.ReadLine());
File.WriteAllLines(path, lines);
Thanks!
Replace following line of code with mention code:
string path = C:\...\text1.text
List<string> lines = File.ReadAllLines(path);
int i = 1;
foreach (var line in lines)
{
Console.WriteLine("{0}. {1}", i, line);
i++;
}
Console.Write("Choose which line to edit: ");
int n = int.Parse(Console.ReadLine());
n--;
Console.Write("{0}. ", n + 1);
lines.Insert(n, Console.ReadLine());
File.WriteAllLines(path, lines.ToArray());
Environment.NewLine Property Gets the newline string defined for this environment.
// Sample for the Environment.NewLine property
using System;
class Sample
{
public static void Main()
{
Console.WriteLine();
Console.WriteLine("NewLine: {0} first line{0} second line{0} third line",
Environment.NewLine);
}
}
/*
This example produces the following results:
NewLine:
first line
second line
third line
*/
Take a look here:
AppendAllText
For all File Methods:
File Methods
The AppendAllText has a signature:
public static void AppendAllText(
string path,
string contents
)
to use:
File.AppendAllText("path/to/file/that/exists/myfile.txt", "Your new line here");
Related
I am trying to save a String Builder to a file but it doesn't make new line.
the output should look like
output without new line
class Program
{
static public void justify(List<string> words, int width)
{
//some code to build the arrays
int ii = 0, jj;
StringBuilder builder = new StringBuilder();
do
{
jj = result[ii];
for(int k = ii; k < jj; k++)
{
builder.Append(words[k] + " ");
}
builder.Append("\n");
ii = jj;
}
while(jj < words.Count);
Console.WriteLine(builder.ToString());
StreamWriter file = new StreamWriter("output.txt");
file.Write(builder.ToString());
file.Close();
}
static void Main(string[] args)
{
string file_extention, file1;
file1 = Console.ReadLine();
file_extention = "C:\\Users\\sayed\\Desktop\\" + file1 + ".txt";
string text = System.IO.File.ReadAllText(#file_extention);
result = text.Split(' ').ToList();
justify(result, 10);
}
}
That's because the you should use \r\n for new lines in Windows. \n is Unix. You should use
builder.AppendLine();
which does this automatically. More precisely, AppendLine() appends a \r\n on non-Unix platforms and a string \n on Unix platforms.
Note that your file does indeed contain the \n which some editors do interpret as line breaks even on Windows. Notepad, for instance, does not.
Replace
builder.Append("\n");
with
builder.Append(Environment.NewLine);
Then open your file with notepad++ instead of window's default text editor.
I believe your \n characters are being ignored by notepad and so they aren't rendering. On Windows machines, it expects a \r\n to render a newline and Environment.NewLine will make sure you get the right one.
I have a small text file, containing a few integers on separate lines.
I wrote the following program (just a function called ReadFromFile) in order to read in the integers and assign them to some variables.
I wonder if I could improve it, and how? I tried reading in integers, but realized I would get errors with StreamReader, so I carried on using strings.
Is there anyway I could improve this program?
All it does is read in the following numbers, assign the first two to two variables, and put the rest in a list.
3
4
8
8
8
8
8
8
So, I will have: var1 = 3 , var2 = 4 , myList = [8,8,8,8,8,8]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace Practice
{
class Program
{
static void Main(string[] args)
{
// Read the specifications from the file.
ReadFromFile();
// Prevent the console window from closing.
Console.ReadLine();
}
/// The function that reads the input specifications from a file.
public static void ReadFromFile()
{
string localPath = #"C:\Desktop\input.txt";
StreamReader sr = new StreamReader(localPath);
// Read all the lines from the file into a list,
// where each list element is one line.
// Each line in the file.
string line = null;
// All lines of the file.
List<string> lines = new List<string>();
while ( ( line = sr.ReadLine() ) != null )
{
lines.Add(line);
Console.WriteLine(line);
}
// Display the extracted parameters.
Console.WriteLine( lines[0] + " var1");
Console.WriteLine( lines[1] + " var2");
// Put the rest in a separate list.
List<int> myList = new List<int>();
for (int i = 2; i < lines.Count; i++)
{
Console.WriteLine("item {0} = {1}", i-1, lines[i] );
myList.Add( Int32.Parse( lines[i] ) );
}
sr.Close();
}
}
}
var vals = File.ReadAllLines(path).Select(int.Parse).ToList();
You might need a Skip(...) if you have header lines; for example to match your for(int i = 2; ...):
var vals = File.ReadAllLines(path).Skip(2).Select(int.Parse).ToList();
You could write it as follow :
public static void ReadFromFile(string localPath) // paremetrizing the path for more flexibility
{
StreamReader sr = new StreamReader(localPath);
// extrating the lines from the file
List<int> lines = Regex.Split(sr.ReadToEnd(), "\r\n").Select(int.Parse).ToList();
// we can close the reader as we don't need it anymore
sr.Close();
Console.WriteLine( lines[0] + " var1");
Console.WriteLine( lines[1] + " var2");
// removing the first 2 elements
lines = lines.Skip(2).ToList();
for (int i = 0; i < lines.Count; i++)
{
Console.WriteLine("item {0} = {1}", i-1, lines[i] );
}
}
I am looking to read from a text file and if a line contains "XYZ" I need to return substrings within that line, then have the next line read for another substring.
There will be several lines that will return the "XYZ" and on each of these I will require the substring from the following line (Each of these will be a different value).
Currently I can return all instances of the substrings in the lines with "XYZ" but then either keep returning the same substring (which should be unique each time) from the line below the first "XYZ" or just, as below, each character individually.
So in the below snippet, from the log. If a line contains XYZ then I need to move to the next line and pull the Date/Time/and Batch Name Number.
XYZ will repeat several times through out the log, with different results each time.
2015-07-02 11:03:13,838 [1] INFO Place (null) (null) (null) – btnAction_Click, Completed Scan for _HAH_Claim_T, XYZ
2015-07-02 11:03:14,432 [1] INFO Place (null) (null) (null) – btnAction_Click, Set batch name 1234567
string[] lines = File.ReadAllLines(#"Text Document.txt");
foreach (string line in lines)
{
int success = line.IndexOf("XYZ");
if (success > 0)
{
string pass = "Pass";
string date = line.Substring(0, 10);
string time = line.Substring(11, 12);
int ID = line.LastIndexOf("XYZ");
if (ID != 0)
{
Console.WriteLine("\n\t" + pass + " Date: {0}\tTime: {1}", date, time);
}
string currentLine;
string batchID;
for (int i = 0; i < lines.Length; i++)
{
currentLine = lines.Skip(6).First();
batchID = currentLine.Substring(100);
Console.WriteLine("\tBatchID{0}", batchID[i]);
}
Console.WriteLine();
}
}
Console.WriteLine("Press any key to exit.");
System.Console.ReadKey();
I do not completely understand the question as it is a bit abstract as to what you want to extract from each line but something like this will hopefully get you on the right track
using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read))
using (var reader = new StreamReader(stream))
{
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
if (line.Contains("XYZ") && !reader.EndOfStream)
{
var nextLine = reader.ReadLine();
var pass = "Pass";
var date = nextLine.Substring(0, 10);
var time = nextLine.Substring(11, 12);
Console.WriteLine("\n\t" + pass + " Date: {0}\tTime: {1}", date, time);
}
}
}
the line variable is the one containing XYZ and next line is the line subsequent to that. If this is not meeting you requirements the please update the question to be a bit more specific
I would say something like this?
string[] lines = File.ReadAllLines(#"Text Document.txt");
for(int i = 0; i < lines.Length(); i++){
if(lines[i].Contains("XYZ")){
string pass = "Pass";
string date = line.Substring(0, 10);
string time = line.Substring(11, 12);
Console.WriteLine("\n\t" + pass + " Date: {0}\tTime: {1}", date, time);
// Retrieve the value in the next line
string nextLineAfterXYZ = lines[i + 1];
batchID = nextLineAfterXYZ.Substring(100);
Console.WriteLine("\tBatchID{0}", batchID);
}
}
You should add some error-handling, in case it's the last line (IndexOutOfBound) etc.
string[] lines = File.ReadAllLines(#"E:Sum.txt");
string str = string.Empty;
foreach (string line in lines)
{
if (line.Contains("x"))
{
str += line;
Console.WriteLine();
continue;
}
break;
}
Console.WriteLine("Press any key to exit.");
System.Console.ReadKey();
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.
i know how to make a console read two integers but each integer by it self like this
int a = int.Parse(Console.ReadLine());
int b = int.Parse(Console.ReadLine());
if i entered two numbers, i.e (1 2), the value (1 2), cant be parse to integers
what i want is if i entered 1 2 then it will take it as two integers
One option would be to accept a single line of input as a string and then process it.
For example:
//Read line, and split it by whitespace into an array of strings
string[] tokens = Console.ReadLine().Split();
//Parse element 0
int a = int.Parse(tokens[0]);
//Parse element 1
int b = int.Parse(tokens[1]);
One issue with this approach is that it will fail (by throwing an IndexOutOfRangeException/ FormatException) if the user does not enter the text in the expected format. If this is possible, you will have to validate the input.
For example, with regular expressions:
string line = Console.ReadLine();
// If the line consists of a sequence of digits, followed by whitespaces,
// followed by another sequence of digits (doesn't handle overflows)
if(new Regex(#"^\d+\s+\d+$").IsMatch(line))
{
... // Valid: process input
}
else
{
... // Invalid input
}
Alternatively:
Verify that the input splits into exactly 2 strings.
Use int.TryParse to attempt to parse the strings into numbers.
You need something like (no error-checking code)
var ints = Console
.ReadLine()
.Split()
.Select(int.Parse);
This reads a line, splits on whitespace and parses the split strings as integers. Of course in reality you would want to check if the entered strings are in fact valid integers (int.TryParse).
Then you should first store it in a string and then split it using the space as token.
Read the line into a string, split the string, and then parse the elements. A simple version (which needs to have error checking added to it) would be:
string s = Console.ReadLine();
string[] values = s.Split(' ');
int a = int.Parse(values[0]);
int b = int.Parse(values[1]);
string[] values = Console.ReadLine().Split(' ');
int x = int.Parse(values[0]);
int y = int.Parse(values[1]);
in 1 line, thanks to LinQ and regular expression (no type-checking neeeded)
var numbers = from Match number in new Regex(#"\d+").Matches(Console.ReadLine())
select int.Parse(number.Value);
string x;
int m;
int n;
Console.WriteLine("Enter two no's seperated by space: ");
x = Console.ReadLine();
m = Convert.ToInt32(x.Split(' ')[0]);
n = Convert.ToInt32(x.Split(' ')[1]);
Console.WriteLine("" + m + " " + n);
This Should work as per your need!
public static class ConsoleInput
{
public static IEnumerable<int> ReadInts()
{
return SplitInput(Console.ReadLine()).Select(int.Parse);
}
private static IEnumerable<string> SplitInput(string input)
{
return Regex.Split(input, #"\s+")
.Where(x => !string.IsNullOrWhiteSpace(x));
}
}
int a, b;
string line = Console.ReadLine();
string[] numbers= line.Split(' ');
a = int.Parse(numbers[0]);
b = int.Parse(numbers[1]);
Try this:
string numbers= Console.ReadLine();
string[] myNumbers = numbers.Split(' ');
int[] myInts = new int[myNumbers.Length];
for (int i = 0; i<myInts.Length; i++)
{
string myString=myNumbers[i].Trim();
myInts[i] = int.Parse(myString);
}
Hope it helps:)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SortInSubSet
{
class Program
{
static int N, K;
static Dictionary<int, int> dicElements = new Dictionary<int, int>();
static void Main(string[] args)
{
while (!ReadNK())
{
Console.WriteLine("***************** PLEASE RETRY*********************");
}
var sortedDict = from entry in dicElements orderby entry.Key/3 , entry.Value ascending select entry.Value;
foreach (int ele in sortedDict)
{
Console.Write(ele.ToString() + " ");
}
Console.ReadKey();
}
static bool ReadNK()
{
dicElements = new Dictionary<int, int>();
Console.WriteLine("Please entere the No. of element 'N' ( Between 2 and 9999) and Subset Size 'K' Separated by space.");
string[] NK = Console.ReadLine().Split();
if (NK.Length != 2)
{
Console.WriteLine("Please enter N and K values correctly.");
return false;
}
if (int.TryParse(NK[0], out N))
{
if (N < 2 || N > 9999)
{
Console.WriteLine("Value of 'N' Should be Between 2 and 9999.");
return false;
}
}
else
{
Console.WriteLine("Invalid number: Value of 'N' Should be greater than 1 and lessthan 10000.");
return false;
}
if (int.TryParse(NK[1], out K))
{
Console.WriteLine("Enter all elements Separated by space.");
string[] kElements = Console.ReadLine().Split();
for (int i = 0; i < kElements.Length; i++)
{
int ele;
if (int.TryParse(kElements[i], out ele))
{
if (ele < -99999 || ele > 99999)
{
Console.WriteLine("Invalid Range( " + kElements[i] + "): Element value should be Between -99999 and 99999.");
return false;
}
dicElements.Add(i, ele);
}
else
{
Console.WriteLine("Invalid number( " + kElements[i] + "): Element value should be Between -99999 and 99999.");
return false;
}
}
}
else
{
Console.WriteLine(" Invalid number ,Value of 'K'.");
return false;
}
return true;
}
}
}
I have a much simpler solution, use a switch statement and write a message for the user in each case, using the Console.write() starting with a ("\n").
Here's an example of filling out an array with a for loop while taking user input. * Note: that you don't need to write a for loop for this to work*
Try this example with an integer array called arrayOfNumbers[] and a temp integer variable. Run this code in a separate console application and Watch how you can take user input on the same line!
int temp=0;
int[] arrayOfNumbers = new int[5];
for (int i = 0; i < arrayOfNumbers.Length; i++)
{
switch (i + 1)
{
case 1:
Console.Write("\nEnter First number: ");
//notice the "\n" at the start of the string
break;
case 2:
Console.Write("\nEnter Second number: ");
break;
case 3:
Console.Write("\nEnter Third number: ");
break;
case 4:
Console.Write("\nEnter Fourth number: ");
break;
case 5:
Console.Write("\nEnter Fifth number: ");
break;
} // end of switch
temp = Int32.Parse(Console.ReadLine()); // convert
arrayOfNumbers[i] = temp; // filling the array
}// end of for loop
The magic trick here is that you're fooling the console application, the secret is that you're taking user input on the same line you're writing your prompt message on. (message=>"Enter First Number: ")
This makes user input look like is being inserted on the same line. I admit it's a bit primitive but it does what you need without having to waste your time with complicated code for a such a simple task.