вскочите в строку файла c#

как я могу вскочить в некоторую строку в своем файле, например, строку 300 в c:\text.txt?

6
задан jason 20 January 2010 в 17:19
поделиться

5 ответов

Dim arrText() As String 
Dim lineThreeHundred As String

arrText = File.ReadAllLines("c:\test.txt") 

lineThreeHundred = arrText(299) 

Редактировать: C # версия

string[] arrText;
string lineThreeHundred;

arrText = File.ReadAllLines("c:\test.txt");
lineThreeHundred = arrText[299];
1
ответ дан 8 December 2019 в 04:52
поделиться
using (var reader = new StreamReader(@"c:\test.txt"))
{
    for (int i = 0; i < 300; i++)
    {
        reader.ReadLine();
    }
    // Now you are at line 300. You may continue reading
}
13
ответ дан 8 December 2019 в 04:52
поделиться

Пара вещей, которые я заметил:

  1. Microsoft's Использование образца Constructor Streamreader Проверки Будет ли файл в первую очередь.

  2. Вы должны уведомить пользователя, через сообщение на экране или в журнале, если Файл либо не существует, либо короче, чем мы ожидали. Это позволяет Вы знаете о любых неожиданных ошибки, если они случится, пока вы Отладка других частей системы. Я понимаю, что это не была частью вашего оригинальный вопрос, но это хорошо упражняться.

Так что это сочетание нескольких других ответов.

string path = @"C:\test.txt";
int count = 0;

if(File.Exists(path))
{
  using (var reader = new StreamReader(@"c:\test.txt"))
  {
    while (count < 300 && reader.ReadLine() != null)
    {
      count++;
    }

    if(count != 300)
    {
      Console.WriteLine("There are less than 300 lines in this file.");
    }
    else
    {
      // keep processing
    }
  }
}
else
{
  Console.WriteLine("File '" + path + "' does not exist.");
}
1
ответ дан 8 December 2019 в 04:52
поделиться
/// <summary>
/// Gets the specified line from a text file.
/// </summary>
/// <param name="lineNumber">The number of the line to return.</param>
/// <param name="path">Identifies the text file that is to be read.</param>
/// <returns>The specified line, is it exists, or an empty string otherwise.</returns>
/// <exception cref="ArgumentException">The line number is negative, or the path is missing.</exception>
/// <exception cref="System.IO.IOException">The file could not be read.</exception>
public static string GetNthLineFromTextFile(int lineNumber, string path)
{
    if (lineNumber < 0)
        throw new ArgumentException(string.Format("Invalid line number \"{0}\". Must be greater than zero.", lineNumber));
    if (string.IsNullOrEmpty(path))
        throw new ArgumentException("No path was specified.");

    using (System.IO.StreamReader reader = new System.IO.StreamReader(path))
    {
        for (int currentLineNumber = 0; currentLineNumber < lineNumber; currentLineNumber++)
        {
            if (reader.EndOfStream)
                return string.Empty;
            reader.ReadLine();
        }
        return reader.ReadLine();
    }
}
0
ответ дан 8 December 2019 в 04:52
поделиться

Линейные файлы не предназначены для случайного доступа. Таким образом, вы должны искать через файл, чтение и отказавшись от необходимого количества строк.

Современный подход:

class LineReader : IEnumerable<string>, IDisposable {
        TextReader _reader;
        public LineReader(TextReader reader) {
            _reader = reader;
        }

        public IEnumerator<string> GetEnumerator() {
            string line;
            while ((line = _reader.ReadLine()) != null) {
                yield return line;
            }
        }

        IEnumerator IEnumerable.GetEnumerator() {
            return GetEnumerator();
        }

        public void Dispose() {
            _reader.Dispose();
        }
    }

Использование:

// path is string
int skip = 300;
StreamReader sr = new StreamReader(path);
using (var lineReader = new LineReader(sr)) {
    IEnumerable<string> lines = lineReader.Skip(skip);
    foreach (string line in lines) {
        Console.WriteLine(line);
    }
}

Простой подход:

string path;
int count = 0;
int skip = 300;
using (StreamReader sr = new StreamReader(path)) {
     while ((count < skip) && (sr.ReadLine() != null)) {
         count++;
     }
     if(!sr.EndOfStream)
         Console.WriteLine(sr.ReadLine());
     }
}
9
ответ дан 8 December 2019 в 04:52
поделиться
Другие вопросы по тегам:

Похожие вопросы: