473,396 Members | 1,892 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

writing a structure to a binary file

Hi

I need to write the contents of a structure to a binary file - there is one
string and 2 integers, but I can't seem to figure out how to write the data
correctly.

If I am simply writing text to a file there is no problem - that starts when
I attempt to write the structure.

Can someone help me out, please?

Thanks

Phil
Nov 21 '05 #1
5 4309
* "Phil Kelly" <ph********@infatech.com> scripsit:
I need to write the contents of a structure to a binary file - there is one
string and 2 integers, but I can't seem to figure out how to write the data
correctly.

If I am simply writing text to a file there is no problem - that starts when
I attempt to write the structure.


'FileOpen', 'FileClose', 'FilePut', 'FileGet'.

--
M S Herfried K. Wagner
M V P <URL:http://dotnet.mvps.org/>
V B <URL:http://dotnet.mvps.org/dotnet/faqs/>
Nov 21 '05 #2
That article has an section "Save Settings" that shows one way of saving
settings to disk:

http://msdn.microsoft.com/library/de...un03282003.asp

************************************************** **********************
Here is some code I've gathered that uses Isolated Storage:

Imports System.IO
Imports System.IO.IsolatedStorage
Imports Microsoft.Win32

Public Class UserSettings

Private Shared Function _
GetIEDefaultSaveLocation() As String
'When you download a file from IE,
'it defaults to the last location
'you downloaded a file to, this code
'just pulls that location out of the
'registry. If the setting isn't available,
'the user's My Documents folder is used
'as a default.
Dim saveDir As String
Try
Dim IEMain As RegistryKey
IEMain = Registry.CurrentUser.OpenSubKey _
("Software\Microsoft\Internet Explorer\Main", _
False)

saveDir = IEMain.GetValue("Save Directory", _
Nothing)
If saveDir Is Nothing Then
'default to user's My Documents folder
saveDir = Environment.GetFolderPath( _
Environment.SpecialFolder.Personal)
End If
Catch ex As Exception
MsgBox(ex.ToString)
saveDir = Directory.GetDirectoryRoot( _
Application.StartupPath)
End Try
Return saveDir
End Function

Public Shared Function GetSettings() _
As Options
Try
Dim m_Options As Options
Dim settingsPath As String = "settings.xml"
Dim isf As IsolatedStorageFile
isf = IsolatedStorageFile.GetUserStoreForAssembly

If isf.GetFileNames(settingsPath).Length > 0 Then
Dim myXMLSerializer As New _
Xml.Serialization.XmlSerializer( _
GetType(Options))
m_Options = CType( _
myXMLSerializer.Deserialize( _
New IsolatedStorageFileStream _
(settingsPath, IO.FileMode.Open, _
IO.FileAccess.Read)), Options)
Else
m_Options = New Options()
m_Options.defaultSaveLocation = _
GetIEDefaultSaveLocation()
End If
Debug.WriteLine(m_Options.defaultSaveLocation)
Return m_Options
Catch ex As System.Exception
MsgBox(ex.ToString)
Return Nothing
End Try
End Function

Public Shared Sub SaveSettings( _
ByVal currentSettings As Options)
Try
Dim isf As IsolatedStorageFile
isf = IsolatedStorageFile.GetUserStoreForAssembly

Dim settingsPath As String = "settings.xml"
Dim myXMLSerializer As _
New Xml.Serialization.XmlSerializer( _
GetType(Options))
myXMLSerializer.Serialize( _
New IsolatedStorageFileStream( _
settingsPath, IO.FileMode.Create, _
IO.FileAccess.ReadWrite), _
currentSettings)
Catch ex As System.Exception
MsgBox(ex.ToString)
End Try
End Sub
End Class

<Serializable()> Public Class Options
Dim m_defaultSaveLocation As String

Public Property defaultSaveLocation() As String
Get
Return m_defaultSaveLocation
End Get
Set(ByVal Value As String)
Try
If Path.IsPathRooted(Value) AndAlso _
Not Path.HasExtension(Value) Then
If Not Directory.Exists(Value) Then
Directory.CreateDirectory(Value)
End If
m_defaultSaveLocation = Value
End If
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Set
End Property
End Class

************************************************** ************
Here is another method that just serializes a class to disk:

Public Shared Function LoadSettings() As UserSettings

Dim mySettings As New UserSettings

Dim s As String =
Environment.GetFolderPath(System.Environment.Speci alFolder.ApplicationData)

s &= "\my program\x.bin"

If File.Exists(s) Then

Dim streamOut As FileStream

Try
Dim formatter As New BinaryFormatter
streamOut = New FileStream(s, FileMode.Open,
FileAccess.Read)

mySettings = CType(formatter.Deserialize(streamOut),
UserSettings)

Catch

Finally
streamOut.Close()
End Try
End If

Return mySettings

End Function

Public Shared Sub SaveSettings(ByVal mySettings As UserSettings)
Dim s As String =
Environment.GetFolderPath(System.Environment.Speci alFolder.ApplicationData)

s &= "\my program"

If Not Directory.Exists(s) Then

Directory.CreateDirectory(s)

End If

s &= "\x.bin"

Dim formatter As New BinaryFormatter

Dim streamIn As New FileStream(s, FileMode.Create,
FileAccess.Write)

formatter.Serialize(streamIn, mySettings)

streamIn.Close()

End Sub
<Serializable()> _
Public Class UserSettings
Private _username As String
Public Property UserName() As String
Get
If _username = Nothing Then
Return CurrentUser()
Else
Return _username.ToLower
End If
End Get
Set(ByVal Value As String)
_username = Value.ToLower
End Set
End Property

Private Function CurrentUser() As String
Dim sCurrentuser As String =
System.Security.Principal.WindowsIdentity.GetCurre nt.Name.ToLower
Dim i As Integer = sCurrentuser.IndexOf("\") + 1 ' zero based
sCurrentuser = Mid$(sCurrentuser, i + 1).ToLower

Return sCurrentuser
End Function
End Class

Hopefully that will get you going in the right direction,
Greg

"Phil Kelly" <ph********@infatech.com> wrote in message
news:cg**********@sparta.btinternet.com...
Hi

I need to write the contents of a structure to a binary file - there is one string and 2 integers, but I can't seem to figure out how to write the data correctly.

If I am simply writing text to a file there is no problem - that starts when I attempt to write the structure.

Can someone help me out, please?

Thanks

Phil

Nov 21 '05 #3
"Phil Kelly" <ph********@infatech.com> wrote in message
news:cg**********@sparta.btinternet.com...
Hi

I need to write the contents of a structure to a binary file - there is one string and 2 integers, but I can't seem to figure out how to write the data correctly.

If I am simply writing text to a file there is no problem - that starts when I attempt to write the structure.

Can someone help me out, please?


Phil,

Take a look at the BinaryFormatter class - it might
do what you want.

Here's some code that writes an object to a file:

Dim obj as Object 'to write to file

'populate object

Dim formatter As BinaryFormatter = New BinaryFormatter()
Dim fs As FileStream

fs = File.Open(destinationFile, FileMode.OpenOrCreate, FileAccess.Write)
formatter.Serialize(fs, obj)

Here's some code that reads the object from a file:

Dim obj as Object 'to be read from file
Dim formatter As BinaryFormatter
Dim fs As FileStream

fs = File.Open(sourceFile, FileMode.Open, FileAccess.Read)
obj = formatter.Deserialize(fs)
You need to add a Serialized attribute to the object first,
though.

--
Akin

aknak at aksoto dot idps dot co dot uk
Nov 21 '05 #4
I tried using serialization on a structure before and I couldn't get the
structure to accept the serialization attribute. Maybe I was using the wrong
syntax:

public <serializable> mystruct as structure
public i as integer
public a as string
end structure

The compiler took it but when executed, I kept getting errors. Do you have
an example of how to make a structure serializable?

"Wild Wind" wrote:
"Phil Kelly" <ph********@infatech.com> wrote in message
news:cg**********@sparta.btinternet.com...
Hi

I need to write the contents of a structure to a binary file - there is

one
string and 2 integers, but I can't seem to figure out how to write the

data
correctly.

If I am simply writing text to a file there is no problem - that starts

when
I attempt to write the structure.

Can someone help me out, please?


Phil,

Take a look at the BinaryFormatter class - it might
do what you want.

Here's some code that writes an object to a file:

Dim obj as Object 'to write to file

'populate object

Dim formatter As BinaryFormatter = New BinaryFormatter()
Dim fs As FileStream

fs = File.Open(destinationFile, FileMode.OpenOrCreate, FileAccess.Write)
formatter.Serialize(fs, obj)

Here's some code that reads the object from a file:

Dim obj as Object 'to be read from file
Dim formatter As BinaryFormatter
Dim fs As FileStream

fs = File.Open(sourceFile, FileMode.Open, FileAccess.Read)
obj = formatter.Deserialize(fs)
You need to add a Serialized attribute to the object first,
though.

--
Akin

aknak at aksoto dot idps dot co dot uk

Nov 21 '05 #5
Dennis,

Try this:

<Serializable()> Public mystruct As Structure
Public i As Integer
Public a As String
End Structure

"Dennis" <De****@discussions.microsoft.com> wrote in message
news:18**********************************@microsof t.com...
I tried using serialization on a structure before and I couldn't get the
structure to accept the serialization attribute. Maybe I was using the wrong syntax:

public <serializable> mystruct as structure
public i as integer
public a as string
end structure

The compiler took it but when executed, I kept getting errors. Do you have an example of how to make a structure serializable?

"Wild Wind" wrote:
"Phil Kelly" <ph********@infatech.com> wrote in message
news:cg**********@sparta.btinternet.com...
Hi

I need to write the contents of a structure to a binary file - there
is one
string and 2 integers, but I can't seem to figure out how to write the

data
correctly.

If I am simply writing text to a file there is no problem - that
starts when
I attempt to write the structure.

Can someone help me out, please?


Phil,

Take a look at the BinaryFormatter class - it might
do what you want.

Here's some code that writes an object to a file:

Dim obj as Object 'to write to file

'populate object

Dim formatter As BinaryFormatter = New BinaryFormatter()
Dim fs As FileStream

fs = File.Open(destinationFile, FileMode.OpenOrCreate, FileAccess.Write)
formatter.Serialize(fs, obj)

Here's some code that reads the object from a file:

Dim obj as Object 'to be read from file
Dim formatter As BinaryFormatter
Dim fs As FileStream

fs = File.Open(sourceFile, FileMode.Open, FileAccess.Read)
obj = formatter.Deserialize(fs)
You need to add a Serialized attribute to the object first,
though.

--
Akin

aknak at aksoto dot idps dot co dot uk

Nov 21 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
by: rob | last post by:
hey every1, I've got alot of data to write out to file and it's all just 1's and 0's. It's all stored in 2 dimensional arrays of width 32 and varying height. At the moment it's all just...
6
by: DanielEKFA | last post by:
Hey there :) I was once told that the STL classes had member functions to write their data to disk and to restore that data. Searching google (and why are there no "stl" or "map" manpages?), it...
29
by: Glen | last post by:
Is it possible to write a structure to a file in c...as in c++...?? is it using fwrite?? thanx glen
2
by: phyzics | last post by:
I am porting an application from C++ to C#, and am having trouble finding a way to quickly and efficiently write structures to a binary file. In C++ this is trivial because all that is necessary is...
2
by: DBC User | last post by:
Hi Sharpies, I have a C program I am converting it into C#. Everything is fine except this process creates a 6K byte binary file. This file initially filled with 6K null and then start...
3
by: nicolasg | last post by:
Hi, I'm trying to open a file (any file) in binary mode and save it inside a new text file. After that I want to read the source from the text file and save it back to the disk with its...
6
by: arne.muller | last post by:
Hello, I've come across some problems reading strucutres from binary files. Basically I've some strutures typedef struct { int i; double x; int n; double *mz;
5
by: zehra.mb | last post by:
Hi, I had written application for storing employee data in binary file and reading those data from binary file and display it in C language. But I face some issue with writing data to binary file....
3
by: =?Utf-8?B?UmF5IE1pdGNoZWxs?= | last post by:
Hello, I'm trying to write an array of structures named myStructArray to a binary file and later on read it back. Although I could complete the entire project in C in about 2 minutes, I...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.