I need your help. I have a txt file with many lines of information.
The headers of the file are
Date ReferenceNumber Description
13/06/2013 00000081985 TRF DESDE OTRO BCO 00000000000000972353
0105
Mount Money +50.000,00 344.514,74
Between Description and Mount are many spaces
Here's a image of the file
I need split this line to get all the attributes by separate.
I need, Date = 13/06/2013, ReferenceNumber = 00000081985, ....
I'm trying to use split C# function to separate by (' ') but i only can get the 2 first attributes =(
I hope you can help me! Thanks a lot.
You may want to look to see what the length of each field is because it does look like fixed length data. If so use the String.Substring Method, using the starting position and the max length of each field as inputs.
This looks like you're trying to deal with a fixed length file, which is essentially a file with data that is split based on its physical location in the file (each piece of data is expected to occupy a specific number of characters). Seems to be one of those lesser known functions, but check out TextFieldParser. It's a .NET class specifically made for this sort of thing.
Specifically, check out the property TextFieldType, which can be set to FixedWidth and given a width of each of those fields. Should do exactly what you want.
You can try to do something like this:
StreamReader sr = new StreamReader("path to text file");
string s = sr.ReadToEnd();
s = s.Replace(' ', '!'); //change the space sign with other sign
List<string> strList = s.Split('!').ToList();
strList.RemoveAll(t => t == "");
I know the solution isn't best but I hope it will help you.
Related
Ok, I'm racking my brains over this one. It's pretty simple though (I think).
I'm currently creating a text file as a comma separated string of values.
Later, I read in that file data and then use the .split function to split the data by commas.
I discovered that sometimes one of the description fields in the data conatins an embedded comma, which ends up throwing the split command off.
Is there any special character I could use that could pretty much guarantee wouldn't be in the data, or is there a better way to accomplish this? Thanks!
// Initial Load
fullString = fileName + "," + String.Join(",", fieldValues);
// Access later
String[] valuesArray = myString.Split(',');
Short answer, there's no "simple" way to do it using Split. The best you can hope for is to set the deliminator as something cooky that wouldn't ever get used (but even that's not a guarantee).
The simple method would be to used something like CsvHelper (get it through Nuget) or any of the other dozen or so packages that are designed for parsing CSV.
Just looking to see what the best way to approach the following situation would be.
I am trying to make a small job that reads in a txt file which has a thousand or so lines;
Each line is about 40 characters long (mostly numbers, some letter identifiers).
I have used
DataTable txtCache = new DataTable();
txtCache.Columns.Add(new DataColumn("Column1"));
string[] lines = System.IO.File.ReadAllLines(FILEcheck.Properties.Settings.Default.filePath);
foreach (string line in lines)
{
txtCache.Rows.Add(line);
}
However, what I really want to do is a bit confusing and hard to explain so i'll do my best. An example of line is below:
5498494000584454684840}eD44448774V6468465 Z
In the beginning of that long string is a "84", and then a "58" a little bit later. I need to do a comparison on these two numbers. They could be anything, but only a few combinations are acceptable in the file. They will always be in the same spot and same amount of characters (so it will always be 2 numbers and always in the 4-5 location). So I want to have 3 columns. I want the full string in 1 column, and then the 2 individual smaller numbers in columns of themselves. I can then compare them later on, and if there is an issue, I can return the full string which caused the issue.
Is this possible? I am just not sure how to parse out a substring based on character location and then loading it into a datatable.
Any advice would be appreciated. Thank you,
You could create the columns for each of items you are looking to store (whole string, first number, second number), and then add a row for each of the lines in the input file. You could just use the substring method to parse out the two digit numbers and store them. To do your analysis, you could parse the numbers out from the strings, or whatever else you need to do.
lines[0].Substring(3,2) will give you "84" in your above example. If you want the int, you could use Int32.Parse(lines[0].Substring(3,2))
Substring reference: http://msdn.microsoft.com/en-us/library/aka44szs%28v=vs.110%29.aspx
I'm doing a little program where the data saved on some users are stored in a text file. I'm using Sytem.IO with the Streamwriter to write new information to my text file.
The text in the file is formatted like so :
name1, 1000, 387
name2, 2500, 144
... and so on. I'm using infos = line.Split(',') to return the different values into an array that is more useful for searching purposes. What I'm doing is using a While loop to search for the correct line (where the name match) and I return the number of points by using infos[1].
I'd like to modify this infos[1] value and set it to something else. I'm trying to find a way to replace a word in C# but I can't find a good way to do it. From what I've read there is no way to replace a single word, you have to rewrite the complete file.
Is there a way to delete a line completely, so that I could rewrite it at the end of the text file and not have to worried about it being duplicated?
I tried using the Replace keyword, but it didn't work. I'm a bit lost by looking at the answers proposed for similar problems, so I would really appreciate if someone could explain me what my options are.
If I understand you correctly, you can use File.ReadLines method and LINQ to accomplish this.First, get the line you want:
var line = File.ReadLines("path")
.FirstOrDefault(x => x.StartsWith("name1 or whatever"));
if(line != null)
{
/* change the line */
}
Then write the new line to your file excluding the old line:
var lines = File.ReadLines("path")
.Where(x => !x.StartsWith("name1 or whatever"));
var newLines = lines.Concat(new [] { line });
File.WriteAllLines("path", newLines);
The concept you are looking for is called 'RandomAccess' for file reading/writing. Most of the easy-to-use I/O methods in C# are 'SequentialAccess', meaning you read a chunk or a line and move forward to the next.
However, what you want to do is possible, but you need to read some tutorials on file streams. Here is a related SO question. .NET C# - Random access in text files - no easy way?
You are probably either reading the whole file, or reading it line-for-line as part of your search. If your fields are fixed length, you can read a fixed number of bytes, keep track of the Stream.Position as you read, know how many characters you are going to read and need to replace, and then open the file for writing, move to that exact position in the stream, and write the new value.
It's a bit complex if you are new to streams. If your file is not huge, copying a file line for line can be done pretty efficiently by the System.IO library if coded correctly, so you might just follow your second suggestion which is read the file line-for-line, write it to a new Stream (memory, temp file, whatever), replace the line in question when you get to that value, and when done, replace the original.
It is most likely you are new to C# and don't realize the strings are immutable (a fancy way of saying you can't change them). You can only get new strings from modifying the old:
String MyString = "abc 123 xyz";
MyString.Replace("123", "999"); // does not work
MyString = MyString.Replace("123", "999"); // works
[Edit:]
If I understand your follow-up question, you could do this:
infos[1] = infos[1].Replace("1000", "1500");
I am working on a desktop application develop in C#. what i want to do is to:
Open a text file(.txt) Read Data Line By Line Create a grid type structure(i.e combination of
horizontal and vertical line) Then take first line and display its each char in single cell And the take second line and display its each char in single cell and so on.
Since i am beginner so i don't have any idea that how to acheive this. I only want some suggestions and guidance.
Well, this is actually easy to do provided you compose the correct items together to get your result.
You'll want to look up File operations, string manipulation (as well as the knowledge that a string is nothing but an enumerable of chars), and then some simple looping to get what you want.
At a high level, you'll just be needing to get the math right to display your set of text as a grid in X columns by Y rows.
Use File.ReadAllLines(). It will give you and array of strings - line by line.
For each string returned by ReadAllLines use string.ToCharArray. It will give you an array of symbols in string.
Update:
Number of columns in grid will be equal to max length of char array. Number of rows - to number of lines. Hope, I understood your task correctly.
Sounds like a homework problem?
Use the File class to read your text file. As far as printing the output to the screen, you have many options...if you're building a console application the you could just write characters to the output using the Console methods.
Hint: to split each line of text into characters, use the ToCharArray() method on the String class.
here is how you can read from a text file line by line
int counter = 0;
string line;
// Read the file and display it line by line.
System.IO.StreamReader file =
new System.IO.StreamReader("c:\\test.txt");
while((line = file.ReadLine()) != null)
{
Console.WriteLine (line);
counter++;
}
file.Close();
// Suspend the screen.
Console.ReadLine();
http://msdn.microsoft.com/en-us/library/aa287535(v=vs.71).aspx
I need to extract headstone data from an inscription file (structured text file). From this file I am supposed to extract the name of a deceased person, date of birth (or age) and also personal messages. The application should be able to analyse a raw text file and then extract information and display it in tabular form.
The raw text files looks like this:
In loving memory of/JOHN SMITH/who died on 13.02.07/at age 40/we will
miss you/In loving memory of/JANE AUSTIN/who died on 10.06.98/born on
19.12.80/hope you are well in heaven.
Basically / is a delimiter and the name of a deceased person is always in capital letters. I have tried to use String.Split() and substring methods but I can't get it to work for me; I can only get raw data without the delimiter (Environment.Newline) but I don't know how to extract specific information.
You'll need something like:
Open your data file (System.IO)
For each line, do (tip: pick a stream where you can read line by line)
Split them by "/" getting a string[]
Arrays in C# starts at 0; so splitted[1] will be that name, ans so on
Store that information in a managed collection (maybe to use generics?)
Display that collection in a tabular view
Check out How to: Use Regular Expressions to Extract Data Fields. I know the example is in C++, but the Regex and Match classes should help you get started
Here is another good example of parsing out individual sentences.
I would have thought something like this would do the trick
private static void GetHeadStoneData()
{
using(StreamReader read = new StreamReader("YourFile.txt"))
{
const char Delimter = '/';
string data;
while((data = read.ReadLine()) != null)
{
string[] headStoneInformation = data.Split(Delimter);
//Do your stuff here, e.g. Console.WriteLine("{0}", headStoneInformation[0]);
}
}
}