Read a last line containing string in a text file? - c#

i have a text file:
ABCD - 11111
111212
13121
ABCD - 1213
12312
34534
ABCD - 21312
123123
123123
How do i to read from last line start with 'ABCD' to end of file. In the above example, result is:
ABCD - 21312
123123
123123

If you read the file into a string, you can accomplish this by using Substring and LastIndexOf.
string inputText = "ABCD - 11111\n111212\n13121\n\n\n" +
"ABCD - 1213\n12312\n34534\n\n\nABCD - 21312\n123123\n123123";
string remainingText = inputText.Substring(inputText.LastIndexOf("ABCD"));
LastIndexOf will determine the last index where the string ABCD occurs (in this case, 54).
Substring will then remove all text occurring before that index to give you the result you expect.
Therefore remainingText will contain the value:
ABCD - 21312\n123123\n123123

First read the file into an string then use LastIndexOf("ABCD") to find the position of last occurrence of your pattern and finally use SubString to extract it.
string path = #"c:\temp\MyTest.txt";
string readText = File.ReadAllText(path);
int position = readText.LastIndexOf("ABCD");
string toEnd = readText.Substring(position ,readText.Length - position).

Using the System.IO namespace's method File.ReasAllText will read the content of the txt file. Assign the value to string variable.
File.ReadAllText("sample.txt");
Then find the last occurrence of the string ABCD
// Find the last occurrence of ABCD.
int index = sString.LastIndexOf('ABCD');
Then using substring get the string value from last index.
string subStr = sString.Substring(index);

If you want some performance or efficiency I wouldn't read the entire file into memory (especially if it is going to be big). I would use FileStreams with Seek method to start reading from the end of the file last three lines. The exact implementation depends of your data format. In case you don't have a strict format of last three lines then read from the end byte per byte until you read three new lines. Of course the code is not so simple but you gain the best efficiency.

Related

Find and replace string spanned multiline

I have a file and I need to find a particular string and replace it with another string. The file is created or submitted to us by an external system. The submitted file has 80 characters per line. If a word in the text file doesn't fit into one line, it is split into 2 lines delimited by = symbol at the end of the first line. In the below example, the SAMPLE STRING is split into 2 lines, SAM= in the first line and PLE STRING in the second line. An example is given below
Line 1 text goes here SAM=
PLE STRING and the other texts of the file.
Now I need to find if SAMPLE STRING exists, and then replace with some other sample string. I wrote the below code in C#, but unable to find the string if it spans over multiple lines. Please help.
string filecontents = System.IO.File.ReadAllText("c:\\mytext.txt");
if(filecontents.Contains("SAMPLE STRING"))
{
filecontents = filecontents.Replace("SAMPLE STRING", "SOME_OTHER_STRING");
}
string filecontents = File.ReadAllText("c:\\mytext.txt");
// rebuild the splitted strings
filecontents = filecontents.Replace("=" + System.Environment.NewLine, "");
// remove line breaks from text
filecontents = filecontents.Replace(System.Environment.NewLine, " ");
// no need to use the Contains check, use a straightforward replacement (it will do nothing if the string is not present)
filecontents = filecontents.Replace("SAMPLE STRING", "SOME_OTHER_STRING");
Once this is done, resplit your text into multiple lines with the same criteria. Since the string that replaces your sample has a different length, if you don't perform the replacement using this approach (or an equivalent one) you will end up with your text splitted into lines of unequal length.

Split string from text file

I'm trying to convert string to keys from a text file and I need to split text.
For example:
Code c#
string[] controls = File.ReadAllLines(FilePath);
Keys move up = (Keys)Enum.Parse(type of(Keys),controls[1].Split("|", StringSplitOption.None), true);
In the text file at the line[1] I have :
moveUp |W;
I want to set the char W as keys.
Thanks to reply and sorry if my English looks weird.
If you are interested in string after | , then this should be:
controls[1].Split("|", StringSplitOption.None)
replaced with this:
controls[1].Split("|")[1]
[1] means return the 2nd index value from array which will be created by Split()
If you are trying to get from Line 1 then controls[1] should be controls[0] because arrays are zero index based.

How Can I split A String from the end to some character I want

How can I split a string from the end to some character I want.
Let me explain in example
"C:\Users\Esat\Desktop\BilimResimler\1620855_759701257391419_1132489417_n.jpg"
and I want to cut this part 1620855_759701257391419_1132489417_n.jpg but I have a lot of image and image names always changing so i can not use substring metod.So how can i do this ?
just to add to the answers - if this refers to a file that physically exists on disk, then why not let fileinfo do the work for you?
var path = #"C:\Users\Esat\Desktop\BilimResimler\1620855_759701257391419_1132489417_n.jpg";
System.IO.FileInfo myImageFile = new System.IO.FileInfo(path);
Console.WriteLine(myImageFile.Name); // gives 1620855_759701257391419_1132489417_n.jpg
You can search for the last "\" character and eliminate everything from it, including him.
OR
From 0 to the index of the length of "C:\Users\Esat\Desktop\BilimResimler\" - 1 (37 - 1 if I counted correctly) keep the string and eliminate everything else.
This should do it
string imageNameAndPath=#"C:\Users\Esat\Desktop\BilimResimler\1620855_759701257391419_1132489417_n.jpg"
imageNameAndPath=imageNameAndPath.Substring(0, imageNameAndPath.LastIndexOf('/'));
string FileName = Path.GetFileName(Path)
You can also get your file name using below code.
var path = #"C:\Users\Esat\Desktop\BilimResimler\1620855_759701257391419_1132489417_n.jpg";
string ImgPath = path.Substring(path.LastIndexOf(#"\") + 1);

grab value from string in reverse order

I have file with txt content inside. Content is generated dynamicly and I want to read in reverse order, from end of file to the first matched semicolon, for example:
sad12e1sadsadsadasdasd12e2q3312sdadasdasdasqe21231122123123asd1asda;123456
so I want to grab this 123456 integer, ofcourse this is generated content with random int length.
If you have always the searched text at the end of the string and after a semicolon you could use
string.LastIndexOf(';');
for example
string test = "sad12e1sadsadsadasdasd12e2q3312sdadasdasdasqe21231122123123asd1asda;123456";
int pos = test.LastIndexOf(';');
if(pos >= 0)
string myText = test.Substring(pos+1);
What #Steve said, or just
string value = "sad12e1sadsadsadasdasd12e2q3312sdadasdasdasqe21231122123123asd1asda;123456";
string number = value.Split(';')[1];
though this doesn't handle the case where a semi-colon is missing.

How to check if a position in a string is empty in c#

I have strings with space seperated values and I would like to pick up from a certain index to another and save it in a variable. The strings are as follows:
John Doe Villa Grazia 323334I
I managed to store the id card (3rd column) by using:
if (line.length > 39)
{
idCard = line.Substring(39, 46);
}
However, if I store the name and address (1st and 2nd columns) with Substring there will be empty spaces since they are not of the same length (unlike the id cards). How can I store these 2 values and removing the unneccasry spaces BUT allowing the spaces between name and surname?
Try this:
string line = " John Doe Villa Grazia 323334I";
string name = line.Substring(02, 16).Trim();
string address = line.Substring(18, 23).Trim();
string id = line.Substring(41, 07).Trim();
var values = line.Split(' ');
string name = values[0] + " " + values[1];
string idCard = values[4];
It will be impossible to do without database lookups on names if there aren't spaces for sure in the previous columns.
Are these actually space separated or are they really fix width columns?
By that I mean do the "columns" start at the same index into the string in each case - from the way you're describing the data is sounds like the later i.e. the ID column is always column 39 for 7 characters.
In which case you need to a) pull the columns using the appropriate substring calls as you're already doing and then, use "string ".Trim() to cut off the spaces.
If the rows, are, as it seems fixed with then you don't want to use Split at all.
How can you even get the ID like that, when everything in front of it is of variable length? If that was used for my name, "David Hedlund 323334I", the ID would start at pos 14, not 39.
Try this more dynamic approach:
var name = str.Substring(0, str.LastIndexOf(" "));
var id = str.Substring(str.LastIndexOf(" ")+1);
Looks like your parsing strategy will cause you a lot of trouble. You shouldn't count on the string's size in order to parse it.
Why not save the data in CSV format (John Doe, Villa Grazia, 323334I)?
that way, you can assume that each "column" will be separated by a comma which will make your parsing efforts easier.
Possible "DOH!" question but are you sure they are spaces and not Tabs? Looks like it "could" be a tab seperated file?
Also for browie points you should use String.Empty instead of ' ' for comparisons, its more localisation and memory friendly apparently.
The first approach would be - as already mentioned - a CSV-like structure with a defined token as the field separator.
The second one would be fixed field lengths so you know the first column goes from char 1 to char 20, the second column from char 21 to char 30, and so on.
There is nothing bad about this concept besides that the human readability may be poor if the columns are filled up to their maximum so no spaces remain between them.
You could write a helper function or class which knows about the field lengths and provides an index-based, fault-tolerant access to the particular column. This function would extract the particular string parts and remove the leading and trailing spaces but leave the spaces in between as they are.
If your values have fixed width, best not split it but use the right indexes in your array.
const string input = "John Doe Villa Grazia 323334I";
var name = input.Substring(0, 15).TrimEnd();
var place = input.Substring(16, 38).TrimEnd();
var cardId = input.Substring(39).TrimEnd();
Assuming your values cannot contain two sequential spaces in them we can maybe use " " (double space" as a separator?
The following code will split your string based on the double space
const string input = "John Doe Villa Grazia 323334I";
var entries = input.Split(new[]{" "}, StringSplitOptions.RemoveEmptyEntries)
.Select(s=>s.Trim()).ToArray();
string name = entries[0];
string place = entries[1];
string idCard = entries[2];

Categories