Adding a newline into a string from text file - c#

I have a text file.
I need to add a newline after every new line from text and put every new line surrounded by "" or //.
My Output should be like this:
//Name Disengagement point//
//Description Automated test case to record
disengagement point and force-travel characteristic needed for the
point.//
//StartRecording ForceTravel//
//UserInteraction Please, start attempting to shift the gear to 1st gear.//
//Capture DisengagementPoint UserInput == 1 PressClutch 1 UserInput == 1//
//UserInteraction Please, shift the gear to neutral.//
//ReleaseClutch 100 ForceTravel == LimitReleased//
The method for reading text file:
if (!File.Exists(measurementPath))
{
string[] readText = File.ReadAllLines(measurementPath);
foreach (string s in readText)
{
script = s.Replace(" ", " // ");
char[] separator = new char[] { ' ' };
String[] fields = s.Split(separator);

You can use File.ReadLines, LINQ + String.Format and File.WriteAllLines:
var newLines = File.ReadLines(measurementPath)
.Select(line => String.Format("//{0}//", line))
.ToList();
File.WriteAllLines(measurementPath, newLines);

Related

c# replace last character in every line

How can I replace the last character in every line?
Example:
rtt45|20160706|N2413847|aneess kim|20160727|
rtt45|20160706|N2247673|ram thomus|20160729|
rtt45|20160706|N2373039|rohan kumar|20160721|
I have tried
string rr = "D:\\temp\\test_07272016020733.txt";
string lines = File.ReadAllText(rr);
lines =lines.Replace("| \n", "\n");
How about something like:
string rr = "D:\\temp\\test_07272016020733.txt";
string[] lines = File.ReadAllLines(rr);
lines = lines.Select(x => x.TrimEnd('|')).ToArray();
EDIT: If you want it all in a single string to end with:
var text = string.join(Environment.NewLine, lines);
For completeness, in a single line keeping variable names in tact:
string rr = "D:\\temp\\test_07272016020733.txt";
string lines = string.Join(Environment.NewLine, File.ReadLines(rr).Select(x => x.TrimEnd('|')));
replace
lines = lines.Replace("| \n", "\n");
with
lines = lines.Replace("|" + System.Environment.NewLine, System.Environment.NewLine);
or (equal)
lines = lines.Replace("|\r\n", "\r\n");

Replace List<string> with words from a file, keep the order

public static List<string> items = new List<string>() { "a","b","c","d","e" };
I am trying to change each of those from loading a file and replacing with their current inventory.
if (File.Exists("darColItems.txt") == true)
{
char c = ',';
StreamReader st = new StreamReader("darColItems.txt");
temp = st.ReadToEnd().ToCharArray();
foreach (c in temp)
{
}
st.Close();
}
Edit: Taking a file such as: iron,bronze,gold,diamond,iron and taking each name and place it into the list for each spot.
File.txt: "string1","string2","string3","string4","string5"
Startup of program:
List inventory (current):
"a","b","c","d","e"
Load inventory....
List inventory (final):
"string1","string2","string3","string4","string5"
Assuming that you actually want to replace all items in the list with all items in the file in the order of occurence and the delimiter is comma. You could use String.Split:
items = File.ReadAllText("path").Split(new [] { ',' }, StringSplitOptions.None).ToList();
If you have quotes around the words in the file which you want to remove, you can use String.Trim:
items = File.ReadAllText("path")
.Split(new char[] { ',' }, StringSplitOptions.None)
.Select(s => s.Trim('"', ' ')) // remove quotes + spaces at the beginning and end
.ToList();
//keep filename in a constant/variable for easy reuse (better, put it in a config file)
const string SourceFile = "darColItems.txt";
//what character separates data elements (if the elements may contain this character you may instead want to look into a regex; for now we'll keep it simple though, & assume that's not the case
const char delimeter = ',';
//here's where we'll store our values
var values = new List<string>();
//check that our input file exists
if (File.Exists(SourceFile))
{
//using statement ensures file is closed & disposed, even if there's an error mid-process
using (var reader = File.OpenText(SourceFile))
{
string line;
//read each line until the end of file (at which point the line read will be null)
while ((line = reader.ReadLine()) != null)
{
//split the string by the delimiter (',') and feed those values into our list
foreach (string value in line.Split(delimiter)
{
values.Add(value);
}
}
}
}

I need closing ) parenthesis?

my code adding semicolon to end of each line... But I need closing ) parenthesis on my second sentence on richtextbox1. how can I add correctly?
NOT: my second sentence can end with any word, which means succession s.Endwith("no") replace ("no",");").....not a option to use!.
My code only puts ; end of each line
string[] lines = richTextBox1.Lines;
List<string> ToAdd = new List<string>();
string filter = ")";
foreach (string s in lines)
{
string hold = s;
if (s.EndsWith(")"))
hold = s.Replace(filter, ";");
}
richTextBox1.Lines = ToAdd.ToArray();
My Result
This is my sentence (Yes);
This is my sentence (Yes) or no;
This is my sentence (Yes);
This is my sentence (Yes);
I want this result:
This is my sentence (Yes);
This is my sentence (Yes) or no);
This is my sentence (Yes);
This is my sentence (Yes);
Try following:
OracleDataReader reader = Command.ExecuteReader())
{
reader.Read();
string[] split = reader[0].ToString().Trim().Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
foreach (string line in split)
{
if(line.Trim()==")")
richTextBox1.AppendText(line.Trim() + ";" + Environment.NewLine);
else
richTextBox1.AppendText(line.Trim() + Environment.NewLine);
}
}
Edit:
Before for loop, try following:
if(reader[0].toString()==")")
reader[0].append(";")
(Not exactly the same, but can continue with this logic)

Reading text files one word at a time until end of file and display on textblock

I am looking for a way I can read a text file, one word at a time, until the end of the file.
This is my code at the moment but it is only reading one word from the file and no more.
How can I process the entire file?
var ResourceStream = Application.GetResourceStream(new Uri("test.txt",UriKind.Relative));
using (Stream myFileStream = ResourceStream.Stream)
{
string s = "";
StreamReader myStreamReader = new StreamReader(myFileStream);
s = myStreamReader.ReadToEnd();
s = s.Trim();
//tlbwords.Text = s;
char[] delimiters = { '\n', '\r' };
string[] words = s.Split(delimiters);
tlbwords.Text = words[0];
}
}
}
}
You can use String[] lines = File.ReadAllLines(fileName); and then separate the words.
Using LINQ to get all words:
var words = File
.ReadAllLines(fileName)
.SelectMany(line -> line.Split(' '))
.Where(word => !string.IsNullOrWhiteSpace())
.ToArray();
Edit with Julián Urbano suggestion:
var words = File
.ReadAllLines(fileName)
.SelectMany(line -> line.Split(' ', StringSplitOptions.RemoveEmptyEntries))
.ToArray();
Why not use:
textbox1.Text = File.ReadAllText(filename);
and set Multiline to true

Exception "String cannot be of Zero length"

We are trying to read each word from a text file and replace it with another word.
For smaller text files, it works well. But for larger text files we keep getting the exception: "String cannot be of zero length.
Parameter name: oldValue "
void replace()
{
string s1 = " ", s2 = " ";
StreamReader streamReader;
streamReader = File.OpenText("C:\\sample.txt");
StreamWriter streamWriter = File.CreateText("C:\\sample1.txt");
//int x = st.Rows.Count;
while ((line = streamReader.ReadLine()) != null)
{
char[] delimiterChars = { ' ', '\t' };
String[] words = line.Split(delimiterChars);
foreach (string str in words)
{
s1 = str;
DataRow drow = st.Rows.Find(str);
if (drow != null)
{
index = st.Rows.IndexOf(drow);
s2 = Convert.ToString(st.Rows[index]["Binary"]);
s2 += "000";
// Console.WriteLine(s1);
// Console.WriteLine(s2);
streamWriter.Write(s1.Replace(s1,s2)); // Exception occurs here
}
else
break;
}
}
streamReader.Close();
streamWriter.Close();
}
we're unable to find the reason.
Thanks in advance.
When you do your string.Split you may get empty entries if there are multiple spaces or tabs in sequence. These can't be replaced as the strings are 0 length.
Use the overload that strips empty results using the StringSplitOptions argument:
var words = line.Split(delimiterChars, StringSplitOptions.RemoveEmptyEntries);
The exception occurs because s1 is an empty string at some point. You can avoid this by replacing the line
String[] words = line.Split(delimiterChars);
with this:
String[] words = line.Split(delimiterChars, StringSplitOptions.RemoveEmptyEntries);
You want to change your Split method call like this:
String[] words = line.Split(delimiterChars,StringSplitOptions.RemoveEmptyEntries);
It means that s1 contains an empty string ("") which can happen if you have two consecutive white spaces or tabs in your file.

Categories

Resources