I have a string in C# and would like to get text from specific line, say 65. And if file does not have so many lines I would like to get "". How to do this?
If you have a string instance already, you can use String.Split
to split each line and check if line 65 is available and if so use it.
If the content is in a file use File.ReadAllLines
to get a string array and then do the same check mentioned before. This will work well for small files, if your file is big consider reading one line at a time.
using (var reader = new StreamReader(File.OpenRead("example.txt")))
{
reader.ReadLine();
}
Other than taking advantage of a specific file structure and lower level file operations, I don't think theres any faster way than to read 64 lines, discard them and then read the 65th line and keep it. At each step, you can easily check if you've read the entire file.
Quick and easy, assuming \r\n or \n is your newline sequence
string GetLine(string text, int lineNo)
{
string[] lines = text.Replace("\r","").Split('\n');
return lines.Length >= lineNo ? lines[lineNo-1] : null;
}
You could use a System.IO.StringReader
over your string. Then you could use ReadLine()
until you arrived at the line you wanted or ran out of string.
As all lines could have a different length, there is no shortcut to jump directly to line 65.
When you Split()
a string you duplicate it, which would also double the memory consumption.
What you can do is, split the string based on the newline character.
string[] strLines = yourString.split(Environment.NewLine);
if(strLines.Length > lineNumber)
{
return strLines[lineNumber];
}