Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Here's two ways:</p> <pre><code>public static string ReadSpecificLine1( string path , int lineNumber ) { int cnt = 0 ; string desiredLine = File.ReadAllLines( path ).FirstOrDefault( x =&gt; (++cnt == lineNumber) ) ; return desiredLine ; } public static string ReadSpecificLine2( string path , int lineNumber ) { string desiredLine = null ; using ( FileStream stream = new FileStream( path , FileMode.Open , FileAccess.Read , FileShare.Read ) ) using ( StreamReader reader = new StreamReader( stream ) ) { int i = 0 ; string line = null ; while ( null != (line=reader.ReadLine()) &amp;&amp; ++i &lt; lineNumber ) { } if ( i == lineNumber &amp;&amp; line != null ) { desiredLine = line ; } return desiredLine ; } } </code></pre> <p>If you know for certain that your file</p> <ul> <li><p>Contains only characters that comprise a single, fixed-size Unicode code unit in the file's unicode encoding scheme, <strong>and</strong></p></li> <li><p>has fixed length lines (records)</p></li> </ul> <p>Then you can <code>seek()</code> directly to the line in question, as in this example using UTF-16 encoding, thus saving extraneous I/O operations:</p> <pre><code>public static string ReadSpecificLineFromUTF16EncodedFile( string path , int lineNumber ) { string desiredLine = null ; using ( FileStream stream = new FileStream( path , FileMode.Open , FileAccess.Read , FileShare.Read ) ) using ( StreamReader reader = new StreamReader( stream , Encoding.Unicode ) ) { Encoding UTF_16 = Encoding.Unicode ; const int RECORD_LENGTH_IN_CHARS = 80 ; const int FIXED_CODE_UNIT_SIZE_IN_OCTETS = sizeof(char) ; // size of a UTF-16 code unit (char) in octets const int RECORD_LENGTH_IN_OCTETS = RECORD_LENGTH_IN_CHARS * FIXED_CODE_UNIT_SIZE_IN_OCTETS ; long offset = (lineNumber-1)*RECORD_LENGTH_IN_OCTETS ; if ( offset &lt; 0 ) throw new ArgumentOutOfRangeException("lineNumber") ; if ( offset &lt;= stream.Length ) { stream.Seek( offset , SeekOrigin.Begin ) ; desiredLine = reader.ReadLine() ; } } return desiredLine ; } </code></pre> <p>Note that this will <strong>only</strong> work if the above two conditions are true.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload