Importing text files lines to certain text and combo boxes - c#

My apologies upfront if this is posted incorrectly. I will promptly take it down if requested.
I am (very much) a beginner of C# and Visual Studio. I have created a little program that exports data into a text file. See this picture:
You'll see my program, the export feature, and the exported text file.
Now I want to do the reverse and import these created text files into my program.
My first guess is to somehow call the lines (or strings). But how would I get just pieces of the line into my text fields or combo boxes? For instance, see POINT 1 in the text file and the program.
I am not posting any code because I have not written any yet as I do not know where to start. Yet, I can post any of my existing code if requested.
I will do whatever I need to make it easier for you to help. Thank you!

My first question is why you are using a combobox for a number that can supposedly go up to 123? Are there limited options for your values because if not, I would instead use textboxes.
I would start by create a Object class for "Point" accepting 6 parameters for each of the values. Then importing your text file data into your application with some sort of StreamReader or OpenFileDialog. This is some sample code that you can use/change to fit your needs (working with beginning values and Point at the beginning of your line won't work for this code).
Stream myStream;
openFileDialog1.FileName = string.Empty;
openFileDialog1.InitialDirectory = "C:\\";
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
if (extension.Equals(".TXT", compareType))
{
try
{
using (myStream = openFileDialog1.OpenFile())
{
string path = Path.GetDirectoryName(openFileDialog1.FileName);
StreamReader reader = new StreamReader(openFileDialog1.FileName);
string line;
while ((line = reader.ReadLine()) != null)
{
string[] value = line.Split('-'); //Split line based on delimiter
_pointList.Add(new Parameter(value[0], value[1], value[2], value[3], value[4], value[5]));
}
If you want to populate your textbox, you can call each element from your list.
textbox1.Text = _pointList.ElementAt(0).Value1;
Hope this helps!

I'm not so great with comboboxes as I haven't done any winforms stuff in a while, but here's how to get your text file data into your c# program:
string[] fileEntries = Directory.GetFiles(yourPathToFileHere);
This will insert each line of your text file as a string in an array (e.g. line 1 of your textfile = fileEntries[0]. Then you're probably going to want to split the line into individual items of interest so you'll want to use this:
string[] partsOfString = yourString.Split('charToSplitOn');
See if you can solve it yourself from there. If you still need help let me know and we'll go further! : )
EDIT1: A demo of .Split() in action!
string inputString = "POINT 1 123-123-123N 123-123-123W";
string[] results = inputString.Split('-', ' '); //split the input on hyphens and spaces
your results view will look like this:
results[0] = "POINT"
results[1] = "1"
results[2] = "123"
results[3] = "123"
results[4] = "123N"
results[5] = "123"
results[6] = "123"
results[7] = "123W"

Related

Use everything before a specific character

So, I've been learning C# and I need to remove everything after the
":" character.
I've used a StreamReader to read the text file, but then I can't use the Split function, then I tried it by using an int function to import it, but then again I can't use the Split function?
What I want this to do is import a text file that's written like;
name:lastname
name2:lastname2
And so that it only shows name and name2.
I've been searching this for a couple of days but I can't seem to figure it out!
I don't know what I'm doing wrong and how to import the text file without using StreamReader or anything else.
Edit:
I'm trying to post something to a website that goes like;
example.com/q=(name without ":")
Edit 2:
StreamReader list = new StreamReader(#"list.txt");
string reader = list.ReadToEnd();
string[] split = reader.Split(":".ToCharArray());
Console.WriteLine(split);
gives output as;
System.String[]
You've got a few issues here. First, use File.ReadLines() instead of a StreamReader, its much simpler and easier:
IEnumerable<string> lines = File.ReadLines("path/to/file");
Next, your lines variable needs to be iterated so you can get to each line of the collection:
foreach (string line in lines)
{
//TODO: write split logic here
}
Then you have to split each line on the ':' character:
string[] split = line.Split(":");
Your split variable is an array of string (i.e string[]) which means you have to access a specific index of the array if you want to see its value. This is your second issue, if you pass split to Console.WriteLine() under the hood it just calls .ToString() on the object you have passed it, and with a string[] it won't automatically give you all the values, you have to write that yourself.
So if your line variable was: "name:Steve", the split variable would have two indexes and look like this:
//split[0] = "name"
//split[1] = "Steve"
I made a fiddle here that demonstrates.
I your file size small and your name:lastname in one line use:
var lines = File.ReadAllLines("filaPath");
foreach (var line in lines)
{
var array = line.Split(':');
if (array.Length > 0)
{
var name = array[0];
}
}
if name:lastname isn't in new line tell me how it's seprated

How to add text to the line that starts with "hello" in a file

I have a file that contains many lines. There is a line here looking like below:
hello jim jack nina richi sam
I need to add a specific text salmon in this line and change it to below (it could be added anywhere in this line -end -begining - in the middle -doesnt matter ):
hello jim jack nina richi sam salmon
I tried:
string path = #"C:\testFolder\newTestLog.txt";
StreamReader myReader = new StreamReader(path);
string[] allLines = File.ReadAllLines(path);
foreach (string element in allLines) {
if (element.StartsWith("hello"))
{
Console.WriteLine(element);
}
}
myReader.Close();
}
Using this I'm able to read the file line by line and add each line to an array and print that line if that starts with "hello", but I'm not sure how to add text to this line
You should use what Joel answered it's nicer but if you're having trouble implementing it try this. After adding the salmon to the lines that start with hello you can overwrite the txt file by using File.WriteAllLines
string filePath = #"C:\testFolder\newTestLog.txt";
string[] allLines = File.ReadAllLines(filePath);
for(int i = 0; i < allLines.Length; i++)
{
if (allLines[i].StartsWith("hello"))
{
allLines[i] += " salmon";
}
}
File.WriteAllLines(filePath, allLines);
Try this:
string path = #"C:\testFolder\newTestLog.txt";
var lines = File.ReadLines(path).Select(l => l + l.StartsWith("hello")?" salmon":"");
foreach (string line in lines)
Console.WriteLine(line);
Note that this still only writes the results to the Console, as your sample does. It's not clear what you really want to happen with the output.
If you want this saved to the original file, you've opened up a small can of worms. Think of all of the data in your file as if it's stored in one contiguous block1. If you append text to any line in the file, that text has nowhere to go but to overwrite the beginning of the next. As a practical matter, if you need to modify file, this often means either writing out a whole new file, and then deleting/renaming when done, or alternatively keeping the whole file in memory and writing it all from start to finish.
Using the 2nd approach, where we keep everything in memory, you can do this:
string path = #"C:\testFolder\newTestLog.txt";
var lines = File.ReadAllLines(path).Select(l => l + l.StartsWith("hello")?" salmon":"");
File.WriteAllLines(path, lines);
1 In fact, a file may be split into several fragments on the disk, but even so, each fragment is presented to your program as part of a single whole.

Write the data to specific line C#

I have some data and I want to write them to a specific line in notepad using C#.
For example I have two textboxes and the data inside them are "123 Hello", for textBox1, and "565878 Hello2" for textBox2.
When I press SAVE button, those data will be saved into one file but with different line. I want to save the first data in the first line and the second data in the third line.
How can I do this?
This question is too broad. The simple answer is that you write the two lines to a file, but write a newline (either "\r\n" or Environment.NewLine) between each string. That will put the two strings on different lines. If you want the second string on the third line, then you should write two newlines between each string.
If neither of those are the answer, then you need to be a lot more specific about why not. Is the file empty to start with? What have you tried? Where, specifically, are you getting stuck? What platform?
And I really don't see what this has to do with NotePad.
EDIT:
You have clarified that you are starting with an existing text file and want to replace the content at the specified lines.
This is a more complex thing to do, and may be beyond your skills if you are just starting out. The basic approach is this:
Assuming you can read the entire file into memory, load the file into a string. You will have to parse new lines to find the lines you want to replace. You can then just replace those parts of the string with the new data. When finished, write the file back to disk.
If the file is too big to load into memory, then it becomes much more complex. I'm sorry, but since you've done such a poor job of describing the issue, I'm not going to the trouble of going over the details for this case. And such a task probably falls outside the scope of a stackoverflow answer any way.
If you line numbers are not fixed you can do something like below:
class Program
{
private static void Main()
{
var data = "";
const string data1 = "Data1";//First Data
const string data2 = "Data2";//Second Data
const int line1 = 1;//First Data Line
const int line2 = 3;//Second Data Line
var maxNoOfLines = Math.Max(line1, line2);
for (var i = 1; i <= maxNoOfLines; i++)
{
if (i == line1)
{
data += data1 + Environment.NewLine;
}
else if (i == line2)
{
data += data2 + Environment.NewLine;
}
else
{
data += Environment.NewLine;
}
}
File.WriteAllText(#"C:\NOBACKUP\test.txt", data);
}
}
Otherwise if line numbers are fixed it will be much more simpler. You can just remove the loop from above and hardcode the values.

get a set of strings from a text file based on codes in c#

I have a list of codes inside a text file I need to get a set of strings starting from one code to another one.
For example, If I have following data (there could be much more data in between) then I need to get the strings between
BS001 till ESS01
BS001 Customer ID|1234|Site Address||||
SS04,Data LANDMARK HOUSE, LONDON, UNITED KINGDOM|||
ESS01 ||
Currently I was working to read the file and go by each line. But how to take the substring starting from a code to the end of the code as the end of the code can be in any line like 5 or 10.
using (StreamReader sr = File.OpenText(fileName))
{
string s = String.Empty;
while ((s = sr.ReadLine()) != null)
{
SearchStringInaLine(s); // Method to search for ESS01 in the line
}
}
Instead of reading line by line, you can already get the full file contents into your string by using
sr.ReadToEnd();
Then you could build a loop and use
int bs001 = s.IndexOf("BS001");
int es001 = s.IndexOf("ES001");
string finding = s.Substring(bs001 + 5, es001 - bs001 - 5);
plus the offsets of the prvious findings to get all matching text (including line breaks) between BS001 and ES001.

Using StreamReader to read a .text file and split it up into arrays/classes

I need to use something like StreamReader to read a .text file and spit it out into arrays that could be used for a pictureviewer and option boxes, etc. The layout of the text file is something like:
PhotoURL PAGEURL SKU# Option1 Option2 Option3 .etc
[Edit]:
example of text file
http://image.com/book.jpg google.com PG52389 Hardcover Ebook
http://item.com/shirt.jpg google.com SH34920 Small Medium Large
ExamplePhotoUrlHere google.com SE39270 Grey Black Red Blue
Not every item has every single option, so there are some blanks on certain columns.
I know I need to use streamreader to read the text file, but I'm not sure how to split it into a class with arrays and all that.
Possible starting point (just splits on spaces):
var linesAsArrays = File.ReadAllLines(absoluteFilePath).Split();
You'll need to figure out what "column" mean - because from your sample it is unclear how to separate one from another.
Note that it may be better option to find existing CSV reader instead of inventing your own.
I am not going to write a complete solution, but you could do something like this (untested)
char[] separators = { ' ', '\t' };
while(!streamReader.EndOfStream)
{
string line = streamReader.ReadLine();
string[] fields = line.Split(separators, 4);
var result = new
{
PhotoUrl = fields[0],
PageUrl = fields[1],
Sku = fields[2],
Options = fields[3].Split(separators),
};
// Use result
}

Categories

Resources