EvilZone

Programming and Scripting => .NET Framework => : ande October 04, 2010, 04:59:52 PM

: Easy read/write file [.NET]
: ande October 04, 2010, 04:59:52 PM
Here is a quick and simple way of reading/writing files.

Reading binary file.
:
Dim FileContent() as byte = my.computer.filesystem.readallbytes("MyFile.bin")

Reading text file.
:
Dim FileContent() as string = my.computer.filesystem.readalltext("MyFile.txt")


Writing binary file (Overwrite if exist)
:
Dim DataToBeWritten() as byte
My.computer.filesystem.writeallbytes("MyFile.bin", DataToBeWritten, false)

Writing binary file (Append if exist)
:
Dim DataToBeWritten() as byte
My.computer.filesystem.writeallbytes("MyFile.bin", DataToBeWritten, true)

Writing text file. (Overwrite if exist)
:
Dim DataToBeWritten as string
My.computer.filesystem.writealltext("MyFile.txt", DataToBeWritten, false)

Writing text file. (Append if exist)
:
Dim DataToBeWritten as string
My.computer.filesystem.writealltext("MyFile.txt", DataToBeWritten, true)
: Re: Easy read/write file [.NET]
: Huntondoom December 06, 2010, 09:36:31 PM
I usually put it in Try ... Catch, End Try, since it can cause some trouble
: Re: Easy read/write file [.NET]
: Reelix March 28, 2011, 08:15:48 AM
I usually put it in Try ... Catch, End Try, since it can cause some trouble

Using Try / Catch blocks are really meant as a last resort, as they are really rather terrible coding practices :)
: Re: Easy read/write file [.NET]
: ande March 28, 2011, 11:40:43 AM
Using Try / Catch blocks are really meant as a last resort, as they are really rather terrible coding practices :)

When dealing with file system and things that may cause errors often it is a good idea tho
: Re: Easy read/write file [.NET]
: Stackprotector March 28, 2011, 01:20:34 PM
When dealing with file system and things that may cause errors often it is a good idea tho
Always good to write some debug code with it when distributing
: Re: Easy read/write file [.NET]
: debug April 02, 2011, 03:02:40 AM
I'd strongly recommend using the methods under the System.IO namespace instead of using old VB references.

It's as simple as:

File.WriteAllBytes(path, data)
File.WriteAllText(path, stringData)

byte[] data = File.ReadAllBytes(path); //C#
Dim data as Byte() = File.ReadAllBytes(path) 'VB

string stringData = File.ReadAllText(path) //C#
Dim stringData as String = File.ReadAllText(path) 'VB