Random Access Files

A

Alan Roberts

In VB6 I could use random access and fixed record lengths to read specific
records from a test file. Eg the following code would save a LogEntry to a
file at the location specified by RecordNumber.

Private Type LogEntry
Date As String * 20
Number As String * 20
Source As String * 100
Description As String * 100
CRLF As String * 2
End Type
Public Sub RecordError(Num As Long, Source As String, Desc As String)
Dim FF As Integer
Dim CurrentRecord As LogEntry
'set the record values
With CurrentRecord
.Date = Trim(Format$(Now, "DD/MM/YYYY HH:MM:SS"))
.Number = Num
.Source = Trim(Source)
.Description = Trim(Desc)
.CRLF = vbCrLf
End With
'save the record
FF = FreeFile
Open "file.txt" For Random As FF Len = 242
Put FF, RecordNumber, CurrentRecord
Close #FF
End Sub

How do I do this sort of thing in Csharp? I can't seem to find a way to
read/write fixed sized records.

Thanks

Alan
 
N

Nicholas Paldino [.NET/C# MVP]

Alan,

There really isn't a simple way to do this.

The best way to do this would be to declare the LogEntry class with the
properties that you specify. Then, I would have a method which would
perform the serialization of the items into a byte array which is 242 bytes
long.

Then, you would have a method which would open the file, move the file
pointer to the appropriate location, write the record, and then close it.

Hope this helps.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top