Домашняя страница Undo Do Save Карта сайта Обратная связь Поиск по форуму
МИР MS EXCEL - Гость.xls

Вход

Регистрация

Напомнить пароль

 

= Мир MS Excel/Готовые решения

МЕНЮ САЙТА
  • 1
  • 2
  • 3

КАТЕГОРИИ РАЗДЕЛА

ОПРОСЫ
Какой версией Excel Вы пользуетесь?
Всего ответов: 56993
Главная » Готовые решения » VB.NET » Полезные приёмы

Прочитать часть текстового файла в строку
31.03.2015, 21:12

Попробуем считать текстовый файл с определенной строки (StartLine). И не весь, а только определенное количество строк (MaxLines).

Автора функции, к сожалению, не записал. Но функция очень душевная :)

 Public Function ReadFile(ByVal Path As String, Optional ByVal MaxLines As Integer = 0, Optional ByVal StartLine As Integer = 0) As String
 Try
 ' создаем переменные counter (how many lines have been read) и CurrentLine (self explanitory)
 Dim Count As Integer = 0 : Dim CurrentLine As Integer = 0
 Dim sb As New System.Text.StringBuilder ' Create a new StringBuilder
 Dim sr As New System.IO.StreamReader(New System.IO.FileStream(Path, System.IO.FileMode.Open, System.IO.FileAccess.Read)) ' Read file into stream
 While Not sr.EndOfStream
 ' If maxlines is not unlimited (=0) and number of lines exceeds the maxlines exit the loop
 If Not MaxLines = 0 AndAlso Count >= MaxLines Then Exit While
 Dim Line As String = sr.ReadLine ' Read current line of stream
 If Not String.IsNullOrEmpty(Line) Then ' Make sure that the line is not an empty string
 If Not StartLine = 0 Then ' Check if we need to monitor for the line to start reading at
 If CurrentLine >= StartLine Then ' The current line is equal to or greater than the startline
 sb.AppendLine(Line) ' Add line to string builder
 Count += 1
 End If
 Else
 sb.AppendLine(Line) ' Add line to string builder
 Count += 1
 End If
 End If
 CurrentLine += 1 ' Update current line counter
 End While
 sr.Close() ' Close stream reader
 ' Trim the contents of the string builder (so there is no blank trailing line) and return
 Return sb.ToString.Trim
 Catch ex As Exception
 'Debug.Print(ex.ToString) ' Debug the exception so we can see what went wrong
 Return String.Empty ' Return empty string due to exception
 End Try
 End Function
Добавил: nilem |
Просмотров: 2642 | Рейтинг: 0.0/0
Всего комментариев: 0
Добавлять комментарии могут только зарегистрированные пользователи.
[ Регистрация | Вход ]
Яндекс.Метрика Яндекс цитирования
© 2010-2024 · Дизайн: MichaelCH · Хостинг от uCoz · При использовании материалов сайта, ссылка на www.excelworld.ru обязательна!