Click here to Skip to main content
15,881,709 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
My app needs to write data from its Dictionary objects to disk between sessions. WriteAllBytes and ReadAllBytes would be the fastest way, but I do not know how to convert the dictionaries to bytes.

Can someone suggest a solution please? VB.net is used for my app but C# responses will be welcome too.

What I have tried:

directcast, cast functions, searching the www
Posted
Updated 9-Jun-18 4:48am
Comments
[no name] 8-Jun-18 19:30pm    
The data types of your "keys" and "values" should have some bearing on your "serialization strategy".

There is no "one size fits all".

You can use the serialization[^] process to persist a dictionary.
A skeleton of needed code would be:
C#
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

class Test
{
   // A dictionary to save/load
   private Dictionary<int, string> _dictionary = new Dictionary<int, string>();

   // A method to save the dictionary to disk
   void Save(string path) {
      using (FileStream fs = new FileStream(path, FileMode.Create)) {
         BinaryFormatter formatter = new BinaryFormatter();
         formatter.Serialize(fs, _dictionary);
      }
   }

   // A method to load the dictionary from the disk
   void Load(string path) {
      using (FileStream fs = new FileStream(path, FileMode.Open)) {
         BinaryFormatter formatter = new BinaryFormatter();
         _dictionary = (Dictionary<int, string>)formatter.Deserialize(fs);
      }
   }
}

Of course, you may want to add these in nice try..catch blocks so that errors can be handled. But you have the general principle.

Kindly.
 
Share this answer
 
Comments
Member 13784077 8-Jun-18 22:40pm    
VS does not like the line Formatter.Serialize(fs, gwrap.DictScript) and
indicates "Reference to a nonshared member requires an object reference"

Friend Sub Save(ByVal strFileName$)
Dim Path$
Dim bf As New BinaryFormatter

Using fs As FileStream = New FileStream(Path, FileMode.Create)
Formatter.Serialize(fs, gwrap.DictScript)
End Using
End Sub
George Swan 9-Jun-18 4:29am    
An excellent solution. I think that, using this method, any class that's serialized needs to be marked as [Serializable]
phil.o 9-Jun-18 4:32am    
You are right; the class has to be marked with Serializable attribute for this to be possible. Dictionary class is serializable.
Oh, and thanks by the way :)
Member 13784077 9-Jun-18 7:33am    
I still have the same old problem "Reference to a nonshared member requires an object reference?. This screenshot at Google Photos shows my problem at the red underline:

AF1QipNXI8-dODOPYJdXVWt9uRz8SSF8gbgkScwALDhK.html

I hope the link works, otherwise how can I direct readers to my photo?
Member 13784077 9-Jun-18 7:36am    
Well, that did not work. Maybe I can show the problem by posting all the code. The problem is at the line with Formatter.Serialize.

BTW, BinaryFormatter seems to be unused in the original C# code, is it necessary to have it if it is not referenced int the code?
Imports System
Imports System.Collections.Generic
Imports System.IO
Imports System.Linq
Imports System.Runtime.Serialization
Imports System.Runtime.Serialization.Formatters.Binary

<serializable()> Public Class CSessionData

Sub Save(ByVal strFileName$)
Dim bf As New BinaryFormatter
Using fs As FileStream = New FileStream(strFileName, FileMode.Create)
Formatter.Serialize(fs, gwrap.DictScript)
End Using
End Sub
End Class
Option Explicit On
Option Strict On
Imports Excel = Microsoft.Office.Interop.Excel
Imports System.Collections.Generic

Friend Class CWrapperGlobal

    Friend intlstDepToHide As New List(Of Integer)
    Friend strlstCellmodeCellAddresses As New List(Of String)
    Friend spCurrentSpecialParms As cSpecialParms
    Friend blnAbandonImportedDep As Boolean
    Friend blnBad As Boolean
    Friend blnBlankScriptOK As Boolean
    Friend blnChangingWorksheet As Boolean
    Friend blnClosingWorkbook As Boolean
    Friend blnCombinedSketchAndScript As Boolean
    Friend blnCompoundDepBeingProcessed As Boolean
    Friend blnCreateInvisible As Boolean
    Friend blnDidEditScript As Boolean
    Friend blnEstimating As Boolean
    Friend blnFirstSession As Boolean
    Friend blnMainDrawSomeSelected As Boolean
    Friend blnOkForPolyshape() As Boolean
    Friend blnPleaseRedraw As Boolean
    Friend blnValueIsOkay As Boolean
    '****************************
    Friend CellRange As myCellRange
    Friend CellRanges() As myCellRange
    Friend Stopwatch As Diagnostics.Stopwatch = New Diagnostics.Stopwatch
    Friend StopWatchAddLine As Diagnostics.Stopwatch = New Diagnostics.Stopwatch
    Friend StopWatchAddShape As Diagnostics.Stopwatch = New Diagnostics.Stopwatch
    '********************************
    'keep certain dictionaries out of pwrap to reduce its bloat
    Friend DictDragged As New Dictionary(Of Integer, cBaseShape)
    Friend DictKeyboard As New Dictionary(Of Integer, String)
    Friend DictMovements As New Dictionary(Of Integer, cDeltas)
    Friend DictSketchScales As New Dictionary(Of Integer, CSketch)
    Friend DictTextFileFilters As New Dictionary(Of Integer, String)
    Friend DictTextFileFBackup As New Dictionary(Of Integer, String)
    Friend DictTextFileLayers As New Dictionary(Of Integer, String)
    Friend DictTextFileScript As New Dictionary(Of Integer, String)
    Friend DictOperations As New Dictionary(Of Integer, COperation)
    Friend DictRownum2Depnum As New Dictionary(Of Integer, Integer)
    Friend DictScript As New Dictionary(Of Integer, String)
    Friend DictScriptBackupCopy As New Dictionary(Of Integer, String)
    Friend DictScriptToCompare As New Dictionary(Of Integer, String)
    Friend DictSelected As New Dictionary(Of Integer, CTracckkerSelection)
    'Friend DictSettings As New Dictionary(Of Integer, String)
    '********************************
    Friend intAutoShapeTypeBeingMoved%
    Friend intBoundaryNodeCount%
    Friend intBoundaryNodePntNumList%()
    Friend intCallingForm%
    Friend intCellAddressCount%
    Friend intCellRangeDimensions%()
    Friend intCellModeDepFoundCount%
    Friend intCellModeSelCount%
    Friend intCompDepMemberCount%
    Friend intCompoundColor%
    Friend intCSVNumber%
    Friend intCSVNumberLast%
    Friend intCurrentDepictionType%
    Friend intDebugColor%
    Friend intDebugMode%
    Friend intDelete1Insert2%
    Friend intDepsInLayers%()
    Friend intDupeFinds%
    Friend intEntries%
    Friend intErrorNumber%
    Friend intFilterBitHide%
    Friend intFormNumber%
    Friend intFreeFormPointCount%
    Friend intGridlineCount%
    Friend intHelpTopic%
    Friend intHideCommandEnabled%
    Friend intLatestShapeMoved% 'Presumably moved, may simply have been selected
    Friend intLatestShapeSelected%
    Friend intLayerMoves%
    Friend intLineSlant%
    Friend intLineColorRGBSelected%
    Friend sglLineWidthSelected%
    Friend intMidpointYes1No2%
    Friend intNBN%
    Friend intOffsetDepName%
    Friend intOffsetMP%
    Friend intOutputParameterCount%
    Friend intPairsItems%
    Friend intPieSliceArcEndsAt%
    Friend intPieSliceArcPosition%
    Friend intPieSliceArcStartsAt%
    Friend intPieSliceOneLineEndsAt%
    Friend intPieSliceOneLineStartsAt%
    Friend intPieSliceOtherLineEndsAt%
    Friend intPieSliceOtherLineStartsAt%
    Friend intPointInstanceLength%
    Friend intPointListCount%
    Friend intPresentCase%
    Friend intRbnSubParam%
    Friend intRibbonIconNumber%
    Friend intIconNumberStart%
    Friend intSavedShapeCount%
    Friend intScriptRedoRow%
    Friend intScriptSpecialRow%
    Friend intScrollRow%
    Friend intSelPropertyLineCount%
    Friend intSeqNumFound%
    Friend intShapeCountSaved%
    Friend intShowDepNum%
    Friend intShownDtype%
    Friend intShownPosition%
    Friend intSketchShapeCount%
    Friend intTesting%
    Friend intTrace%
    Friend intWarningNumber%
    'Friend PairOfPoints() As MyPairOfPoints
    Friend SelCursorInfo As myCursorActions
    Friend sglAverageMeshSideLength!
    Friend sglClickedCellHeightPnts!
    Friend sglClickedCellLeftPnts!
    Friend sglClickedCellTopPnts!
    Friend sglClickedCellWidthPnts!
    Friend sglClickX1!
    Friend sglClickX2!
    Friend sglClickY1!
    Friend sglClickY2!
    Friend sglCrosshairSize!
    Friend sglDimBoxPntsX!
    Friend sglDimBoxPntsY!
    Friend sglFriendBoxPntsX!
    Friend sglFriendBoxPntsY!
    Friend sglFreeFormDataPnts!(,)
    Friend sglFreeFormOffsetHorzPnts!
    Friend sglFreeFormOffsetVertPnts!
    Friend sglFreeFormScaleHorzPPI!
    Friend sglFreeFormScaleVertPPI!
    Friend sglFudgeFactor!
    Friend sglGridSpacingUU!
    Friend sglGridUU!
    Friend sglHeightOfSelectedShapeBoxPnts!
    Friend sglLeftOfSelectedShapeBoxPnts!
    Friend sglMinimumAspectRatio!
    Friend sglMovedDxPnts!
    Friend sglMovedDyPnts!
    Friend sglOriginalDepictionPntsX1!
    Friend sglOriginalDepictionPntsParm1!
    Friend sglOriginalDepictionPntsY1!
    Friend sglOriginalDepictionPntsParm2!
    Friend sglPPI!
    Friend sglSectorAngleDeg!
    Friend sglTopOfSelectedShapeBoxPnts!
    Friend sglTSCalc!
    Friend sglTSDraw!
    Friend sglUndoValues!()
    Friend sglWidthOfSelectedShapeBoxPnts!
    Friend sglXMovedLeftPnts!
    Friend sglXMovedRightPnts!
    Friend sglXofSelectedPoint!
    Friend sglYMovedBotPnts!
    Friend sglYMovedTopPnts!
    Friend sglYofSelectedPoint!
    Friend sglZoom!
    Friend str123CADLicenseCode$
    Friend str123CADOrderNumber$
    Friend str123CADVersion$
    'Friend strCellModeCellAddr$()
    Friend strColorSelected$
    Friend strDataWorksheetname$
    Friend strDepCodeForIntersection$
    Friend strDrawThis$
    Friend strLineExtras$
    Friend strFeaturesSelected$
    Friend strFormat2DP$
    Friend strFormat3DP$
    Friend strFormulaExtracted$()
    Friend strFQTextFileName$
    Friend strHelpDiagramName$
    Friend strHelpVideoName$
    Friend strIconHelp$
    Friend stringWithStructure$
    Friend strIsUsedInNames$
    Friend strLastDepnameUsed$
    Friend strLatestDepName$
    Friend strLatestShapeSelectedName$
    Friend strLongVariationDesc$
    Friend strMainFormTitle$
    Friend strMembers$
    'Friend strMovedLineName$
    Friend strName$
    Friend strNameProvided$
    Friend strNextCommand$
    Friend strNonModalFormResults$
    Friend strNumberFromTime$
    Friend strNumberFromTimePreviously$
    Friend strPreviousCommand$
    Friend strPushedSelections$
    Friend strIconDescription$
    Friend strRunProgram$
    Friend strScriptFields$()
    Friend strScriptFilename$
    'Friend strScriptHelp$
    Friend strScriptPhrase1$
    Friend strSelectionListItems$()
    Friend strSelectionTextboxLines() As String
    Friend strSpareArray$()
    Friend strTargetName$
    Friend strVariation$
    Friend strVariationsForHelp$
    Friend strWarningMessage$
    Friend strWorkbookName$
    Friend strWorkbookForParm$
    Friend strWorksheetForParm$
    Friend strCellForParm$
    Friend strWorksheetForImport$

    Public Sub New()

        intSeqNumFound% = 0
        ReDim blnOkForPolyshape(c_MaxDepTypes)
        ReDim CellRanges(c_100)
        ReDim intBoundaryNodePntNumList%(c_400)
        ReDim intCellRangeDimensions%(c_100)
        ReDim intDepsInLayers%(c_MaxLayers)
        ReDim sglFreeFormDataPnts!(0 To 100, 0 To 1)
        ReDim sglUndoValues!(c_100)
        'ReDim strCellModeCellAddr$(c_100)
        ReDim strFormulaExtracted$(c_WidthScript)
        ReDim strScriptFields$(c_WidthScript)
        ReDim strSelectionListItems$(c_MaxSelDeps)
        ReDim strSelectionTextboxLines(2 * c_MaxDepTypes)
        ReDim strSpareArray$(c_MaxMembers500)

    End Sub

End Class
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900