How I can copy the text from a TextBox in a textFile? - c#

I created a windows form application and I have a TextBox which has text as a file location like this : C:\DATA\FOLDER.
Also I have a text file in d:\data\test.txtwhich contains many lines but one defined line for Location="" .
How I can copy the location specified in the TextBox in the text file test.txt in the Location="" row, without mentioning the line number ?

You can do it in one line
var path = #"d:\data\test.txt";
File.WriteAllLines(path, File.ReadAllLines(path)
.Select(line => line.StartsWith("Location=\"")
? string.Format("Location=\"{0}\"", textBox1.Text)
: line));
First you read all lines in file and if any of them starts with "Location="" then it will be replaced by the location in text box. At the end you write the result back to the file.
If you don't like to do it in one line (and for me not getting downvoted for it) then you can just split it
var path = #"d:\data\test.txt";
var lines = File.ReadAllLines(path);
var modifiedLines = lines.Select(line =>
{
if (line.StartsWith("Location=\""))
{
return string.Format("Location=\"{0}\"", textBox1.Text);
}
else
{
return line;
}
});
File.WriteAllLines(path, modifiedLines);
I think sometimes writing more code reduces readability!

string text = File.ReadAllText("test.txt");
string filepath=textBox1.Text;
text = text.Replace("Location="" "," Location= "+filepath+");
File.WriteAllText("test.txt", text);

This works too:
IList<string> output = new List<string>();
using (StreamReader sr = new StreamReader("d:\\data\\test.txt"))
{
string line;
while ((line = sr.ReadLine()) != null)
{
if (line.StartsWith("Location=\""))
{
line = String.Format("Location=\"{0}\"", "TextBox.Text");
}
output.Add(line);
}
}
File.WriteAllText("d:\\data\\test.txt", string.Join(Environment.NewLine, output));

Related

How do I split text file using 3 empty lines as a delimiter?

My text file:
TestTest
testtest
testtest
testtesttest
testtesttest
testtestset
testtsetse
testestset
I know how to split it with 1 empty line as a delimiter:
string file = File.ReadAllText(filePath)
string[] files = file.Split('\n');
When I use the next code it gives an error cannot convert from string to char:
string[] files = file.Split("\n\n\n");
But when I try:
string[] files = file.Split("\n\n\n".ToCharArray());
it's not working.
Any ideas?
string[] files = file.Split(Environment.NewLine + Environment.NewLine + Environment.NewLine, StringSplitOptions.RemoveEmptyEntries);
You can read file line by line
string line;
System.IO.StreamReader file = new System.IO.StreamReader(filePath);
while((line = file.ReadLine()) != null)
{
System.Console.WriteLine(line);
}
file.Close();

How to add commas at the end of each line in a text file after using OpenFileDialog?

Ok so i am making a tool for a special need.
There will be .mif files which i can open as a text file and read the content.
Using something simple like
DialogResult openFile = form.openFileDialog1.ShowDialog();
if (openFile == DialogResult.OK)
{
int size = -1;
try
{
//Add commas here
}
catch (IOException)
{
}
}
Now how do i add a comma at the end of each line in a file?
e.g something like this
319621.99946835 110837.002493295
319640.501385461 110850.59860145
319695.199120806 110879.700271183
to something like this (notice the commas at the end of each line)
319621.99946835 110837.002493295,
319640.501385461 110850.59860145,
319695.199120806 110879.700271183,
Now the pattern is different for this and it occurs 1000s of time in one file
Any ideas?
string sFilePath = "Insert.File.Path.Here";
File.WriteAllLines(sFilePath, File.ReadAllLines(sFilePath).Select(x => string.Format("{0},",x)));
How to read a file line by line you will find in this post.
at each line do simply:
CurrentLine = CurrentLine + ",";
If your text file isn't big, you can try this:
var path = "myfile.txt";
var lines = File.ReadAllLines (path);
var newContent = string.Join (",\r\n", lines);
File.WriteAllText (path, newContent);
It will not add comma to last line.
Use the methods of the File class:
public static string[] ReadAllLines(
string path
)
public static void WriteAllLines(
string path,
string[] contents
)
Like this
string[] lines = File.ReadAllLines(openFile.FileName);
for (int i = 0; i < lines.Length; i++) {
lines[i] += ",";
}
File.WriteAllLines(openFile.FileName, lines);

Reading a .txt, Display it in Form, Edit in Form, and Save

I'm relatively new to programming and I've set up a "fairly" simple task for me to work on. What I am trying to accomplish is clicking on a "Settings" button on Form1 that will open and post the results of "config.txt" to labels on Form2.
Config.txt looks like this:
[VERSION] 7544
[WIDTH] 480
[HEIGHT] 768
[SCALE] 1
[UI] 8
[SERVER] 2
[DEMO] 1
[BRIGHT] 50
[CURSOR] 1
I have been able to create the .txt file if it does not exist with default values using
using (StreamWriter sw = new StreamWriter("config.txt"))
{
sw.Write("[DATA1] 7544");
sw.Write("[DATA2] 8");
sw.Write("[DATA3] 2");
}
I'm having issues reading the lines of code separately and displaying them to separate labels.
int counter = 0;
string line;
System.IO.StreamReader file = new System.IO.StreamReader(#"config.txt");
while ((line = file.ReadLine()) != null)
{
//System.Console.WriteLine(line);
string labelTest = string.Format(line);
labelVersRead.Text = "Version: " + line;
counter++;
}
file.Close();
I believe the issue I'm having is saying var line3 = line[3]. I can only get it to output the complete .txt into a single string.
In that case you could have a list.
var list = new List<Config>();
public class Config{
string LabelText
string LabelValue
}
while ((line = file.ReadLine()) != null)
{
//Split the line based on the pattern and build the list object for Labeltext and LabelValue.
//You will have to come up with the logic to split the line into string based on the pattern. Where text in the [] is LabelTesxt and anything followed after ] is LabelValue
list.Add(new Config{LavelText = "VERSION" ,LabelValue="7544"});
counter++;
}
//Once done, you could bind the data to the label
var item = list.Find(item => item.LabelText == "VERSION");
lblVersionLabel.Text = item.LabelValue
It looks like you always overriding the Text for the label.
Use + to append the text.
labelVersRead.Text += "Version: " + line;
Or with new line at the end
labelVersRead.Text += "Version: " + line + "\r\n";
Is it this solve the issue you encounter ?

How to add lines of a text file into individual items on a ListBox (C#)

How would it be possible to read a text file with several lines, and then to put each line in the text file on a separate row in a ListBox?
The code I have so far:
richTextBox5.Text = File.ReadAllText("ignore.txt");
String text = File.ReadAllText("ignore.txt");
var result = Regex.Split(text, "\r\n|\r|\n");
foreach(string s in result)
{
lstBox.Items.Add(s);
}
string[] lines = System.IO.File.ReadAllLines(#"ignore.txt");
foreach (string line in lines)
{
listBox.Items.Add(line);
}
Write a helper method that return the collection of lines
static IEnumerable<string> ReadFromFile(string file)
{// check if file exist, null or empty string
string line;
using(var reader = File.OpenText(file))
{
while((line = reader.ReadLine()) != null)
{
yield return line;
}
}
}
use it
var lines = ReadFromFile(myfile);
myListBox.ItemsSource = lines.ToList(); // or change it to ObservableCollection. also you can add to the end line by line with myListBox.Items.Add()
You should use a streamreader to read the file one line at a time.
using (StreamReader sr = new StreamReader("ignore.txt"))
{
string line;
while ((line = sr.ReadLine()) != null)
listBox1.Items.Add(line);
}
StreamReader info -> http://msdn.microsoft.com/en-us/library/system.io.streamreader.aspx
ListBox info -> http://msdn.microsoft.com/en-us/library/system.windows.forms.listbox.aspx

Parsing individual lines in a robots.txt file with C#

Working on an application to parse robots.txt. I wrote myself a method that pulled the the file from a webserver, and threw the ouput into a textbox. I would like the output to display a single line of text for every line thats in the file, just as it would appear if you were looking at the robots.txt normally, however the ouput in my textbox is all of the lines of text without carriage returns or line breaks. So I thought I'd be crafty, make a string[] for all the lines, make a foreach loop and all would be well. Alas that did not work, so then I thought I would try System.Enviornment.Newline, still not working. Here's the code as it sounds now....how can I change this so I get all the individual lines of robots.txt as opposed to a bunch of text cobbled together?
public void getRobots()
{
WebClient wClient = new WebClient();
string url = String.Format("http://{0}/robots.txt", urlBox.Text);
try
{
Stream data = wClient.OpenRead(url);
StreamReader read = new StreamReader(data);
string[] lines = new string[] { read.ReadToEnd() };
foreach (string line in lines)
{
textBox1.AppendText(line + System.Environment.NewLine);
}
}
catch (WebException ex)
{
MessageBox.Show(ex.Message, null, MessageBoxButtons.OK);
}
}
You are reading the entire file into the first element of the lines array:
string[] lines = new string[] {read.ReadToEnd()};
So all your loop is doing is adding the whole contents of the file into the TextBox, followed by a newline character. Replace that line with these:
string content = read.ReadToEnd();
string[] lines = content.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None);
And see if that works.
Edit: an alternative and perhaps more efficient way, as per Fish's comment below about reading line by line—replace the code within the try block with this:
Stream data = wClient.OpenRead(url);
StreamReader read = new StreamReader(data);
while (read.Peek() >= 0)
{
textBox1.AppendText(read.ReadLine() + System.Environment.NewLine);
}
You need to make the textBox1 multiline. Then I think you can simply go
textBox1.Lines = lines;
but let me check that
Try
public void getRobots()
{
WebClient wClient = new WebClient();
string robotText;
string[] robotLines;
System.Text.StringBuilder robotStringBuilder;
robotText = wClient.DownloadString(String.Format("http://{0}/robots.txt", urlBox.Text));
robotLines = robotText.Split(Environment.NewLine);
robotStringBuilder = New StringBuilder();
foreach (string line in robotLines)
{
robotStringBuilder.Append(line);
robotStringBuilder.Append(Environment.NewLine);
}
textbox1.Text = robotStringBuilder.ToString();
}
Try using .Read() in a while loop instead of .ReadToEnd() - I think you're just getting the entire file as one line in your lines array. Debug and check the count of lines[] to verify this.
Edit: Here's a bit of sample code. Haven't tested it, but I think it should work OK;
Stream data = wClient.OpenRead(url);
StreamReader read = new StreamReader(data);
List<string> lines = new List<string>();
string nextLine = read.ReadLine();
while (nextLine != null)
{
lines.Add(nextLine);
nextLine = read.ReadLine();
}
textBox1.Lines = lines.ToArray();

Categories