'Перед работой необходимо импортировать пространство имен System.IO:

Imports System.IO'

Как создать новый файл?

{codecitation class="brush: vb; gutter: true;" width="500px" }File.Create("c:\Текстовой документ.txt"){/codecitation}

Как проверить существование файла?
{codecitation class="brush: vb; gutter: true;" width="500px" }
Dim FI As IO.FileInfo = New IO.FileInfo("c:\test.txt")
If FI.Exists Then
CheckBase = True
Else
CheckBase = False
End If  {/codecitation}

Как копировать файл?
{codecitation style="brush: xml;"}

File.Copy("c:\Текстовой документ.txt", "c:\Новая папка\Текстовой документ.txt")


{/codecitation}'Таже можно указать третий параметр, который позволит перезаписать конечный файл, в случае, если он существует:
{codecitation style="brush: xml;"}

File.Copy("c:\Текстовой документ.txt", "c:\Новая папка\Текстовой документ.txt", True) 'Если файл "c:\Новая папка\Текстовой документ.txt" существует, он будет перезаписан
{/codecitation}
Как удалить файл?
{codecitation style="brush: xml;"}

File.Delete("c:\Текстовой документ.txt")

{/codecitation}

Запись в текстовый файл:

{codecitation style="brush: xml;"}

        ' Get the directories currently on the C drive. 
        Dim cDirs As DirectoryInfo() = New DirectoryInfo("c:\").GetDirectories()

        ' Write each directory name to a file. 
        Using sw As StreamWriter = New StreamWriter("CDriveDirs.txt")
            For Each Dir As DirectoryInfo In cDirs
                sw.WriteLine(Dir.Name)
            Next 
        End Using 

        'Read and show each line from the file. 
        Dim line As String = "" 
        Using sr As StreamReader = New StreamReader("CDriveDirs.txt")
            Do
                line = sr.ReadLine()
                Console.WriteLine(line)
            Loop Until line Is Nothing 
        End Using.
{/codecitation}

{codecitation style="brush: xml;"}

Try
Dim myWriteFile As New StreamWriter("c:\test.txt")
myWriteFile.WriteLine("hello world")
myWriteFile.Flush()
myWriteFile.Close()
myWriteFile = Nothing
Catch ex As IOException
MsgBox(ex.ToString)
End Try
'или (для Framework 2.x и старше)
Try
Using myWriteFile As New StreamWriter("c:\test.txt")
myWriteFile.WriteLine("hello world")
End Using
Catch ex As IOException
MsgBox(ex.ToString) 'ошибка
End Try
{/codecitation}

Чтение из текстового файла:


{codecitation style="brush: xml;"}

        Try 
            ' Create an instance of StreamReader to read from a file. 
            Dim sr As StreamReader = New StreamReader("TestFile.txt")
            Dim line As String 
            ' Read and display the lines from the file until the end  
            ' of the file is reached. 
            Do
                line = sr.ReadLine()
                Console.WriteLine(Line)
            Loop Until line Is Nothing
            sr.Close()
        Catch E As Exception
            ' Let the user know what went wrong.
            Console.WriteLine("The file could not be read:")
            Console.WriteLine(E.Message)
        End Try 

{/codecitation}

{codecitation style="brush: xml;"}

Try
Dim myReadFile As New StreamReader("c:\test.txt")
'выбор кодировки
'Dim myReadFile As New StreamReader("c:\test.txt",System.Text.Encoding.GetEncoding(1251))'windows-1251
Dim sReadLine As String = ""
While True
sReadLine = myReadFile.ReadLine()
If sReadLine Is Nothing Then
Exit While
Else
MsgBox(sReadLine)
End If
End While
myReadFile.Close()
myReadFile = Nothing
Catch ex As IOException
MsgBox(ex.ToString) 'ошибка
End Try
'или (для Framework 2.x и старше)
Try
Using myReadFile As New StreamReader("c:\test.txt")
'выбор кодировки
'Using myReadFile As New StreamReader("c:\test.txt",System.Text.Encoding.GetEncoding(1251))'windows-1251
Dim sReadLine As String = ""
While True
sReadLine = myReadFile.ReadLine()
If sReadLine Is Nothing Then
Exit While
Else
MsgBox(sReadLine)
End If
End While
End Using
Catch ex As IOException
MsgBox(ex.ToString) 'ошибка
End Try

'для чтения всего файла можно использовать метод ReadToEnd():
'MsgBox(myReadFile.ReadToEnd())

{/codecitation}

Запись в бинарный файл:

{codecitation style="brush: xml;"}


Try
Dim myFileStream As FileStream
myFileStream = New FileStream("C:\Binary.dat", FileMode.Create)
Dim myBinaryWriter As New BinaryWriter(myFileStream)
myBinaryWriter.Write("Привет! Это бинарные данные :)")
myBinaryWriter.Close()
myFileStream.Close()
Catch ex As Exception
MsgBox(ex.ToString) 'ошибка
End Try
'или
Try
Using myFileStream As New FileStream("C:\Binary.dat", FileMode.Create)
Using myBinaryWriter As New BinaryWriter(myFileStream)
myBinaryWriter.Write("Привет! Это бинарные данные :)")
End Using
End Using
Catch ex As Exception
MsgBox(ex.ToString) 'ошибка
End Try

{/codecitation}

Чтение бинарного файла:

{codecitation style="brush: xml;"}

Try
Dim myFileStream As System.IO.FileStream
myFileStream = New System.IO.FileStream("C:\Binary.dat", FileMode.Open)
Dim myBinaryReader As New System.IO.BinaryReader(myFileStream)
'считываем файл в переменную bData
Dim bData() As Byte = myBinaryReader.ReadBytes(myFileStream.Length)
'можно использовать другие методы чтения, например:
'myBinaryReader.ReadString()
myBinaryReader.Close()
myFileStream.Close()
Catch ex As Exception
MsgBox(ex.ToString) 'ошибка
End Try
'или
Try
Using myFileStream As New System.IO.FileStream("C:\Binary.dat", FileMode.Open)
Using myBinaryReader As New System.IO.BinaryReader(myFileStream)
'считываем файл в переменную bData
Dim bData() As Byte = myBinaryReader.ReadBytes(myFileStream.Length)
'можно использовать другие методы чтения, например:
'myBinaryReader.ReadString()
End Using
End Using
Catch ex As Exception
MsgBox(ex.ToString) 'ошибка
End Try

{/codecitation}

 

 

Процедура СохранитьТЗвБДФ(ТЗ, Файл, Кодировка = Неопределено)
    ДБФ = Новый XBase;
    Если Кодировка = Неопределено Тогда
        Кодировка = КодировкаXBase.OEM;
    КонецЕсли;    
    ДБФ.Кодировка = Кодировка;
    
    Для Каждого Колонка ИЗ ТЗ.Колонки Цикл
        Если Колонка.ТипЗначения.СодержитТип(Тип("Строка")) Тогда
            Тип = "S";
            Длина = Колонка.ТипЗначения.КвалификаторыСтроки.Длина;
            Если Длина = 0 Тогда
                Длина = 100;
            КонецЕсли;    
            Точность = 0;
            
        ИначеЕсли Колонка.ТипЗначения.СодержитТип(Тип("Число")) Тогда    
            Тип = "N";
            Длина = Колонка.ТипЗначения.КвалификаторыЧисла.Разрядность;
            Точность = Колонка.ТипЗначения.КвалификаторыЧисла.РазрядностьДробнойЧасти;
            Если Длина = 0 Тогда
                Длина = 15;
                Точность = 3;
            КонецЕсли;    
            
        ИначеЕсли Колонка.ТипЗначения.СодержитТип(Тип("Дата")) Тогда    
            Тип = "D";
            Длина = 0;
            Точность = 0;
            
        ИначеЕсли Колонка.ТипЗначения.СодержитТип(Тип("Булево")) Тогда    
            Тип = "L";
            Дина = 0;
            Точность = 0;
            
        Иначе
            Тип = "S";
            Длина = 100;
            Точность = 0;
        КонецЕсли;    
        
        ДБФ.поля.Добавить(Колонка.Имя, Тип, Длина, Точность);
    КонецЦикла;
    ДБФ.СоздатьФайл(Файл);
    
    Для Каждого Стр ИЗ ТЗ Цикл
        ДБФ.Добавить();
        ЗаполнитьЗначенияСвойств(ДБФ, Стр);
        ДБФ.Записать();
    КонецЦикла;    
КонецПроцедуры