Solved

What is the reverse to this code? - Reading and writing between Text file and DataView/DataSet

Posted on 2006-07-15
4
294 Views
Last Modified: 2012-05-05
The following code sucessfully creates and writes the contents of a DataView (each value seperated by '#') to a Text file. Please can someone give me the code that will correctly read it back?

    Private Sub SaveDBToFile()
          Dim path As String = "C:\Temp\MyFile.txt"

        'Create the file.
        Dim fs As FileStream = File.Create(path)

        Dim myDRV As DataRowView
        For Each myDRV In MyDataView
            For i As Integer = 0 To MyDataView.Table.Columns.Count - 1
                If (Not (myDRV(i) Is DBNull.Value)) Then
                    AddText(fs, CType(myDRV(i), String) + "#")  
                Else
                    AddText(fs, " #")
                End If
            Next
            AddText(fs, Environment.NewLine)
        Next
        fs.Close()
    End Sub

    Private Shared Sub AddText(ByVal fs As FileStream, ByVal value As String)
        Dim info As Byte() = New UTF8Encoding(True).GetBytes(value)
        fs.Write(info, 0, info.Length)
    End Sub
0
Comment
Question by:IvanHowarth
  • 3
4 Comments
 
LVL 14

Accepted Solution

by:
Ramuncikas earned 500 total points
ID: 17115525
       'open file
        Dim fs As New FileStream("C:\Temp\MyFile.txt", FileMode.Open)

        'read file to bytes() array
        Dim bytes() As Byte
        fs.Read(bytes, 0, fs.Length - 1)

        'convert bytes to string
        Dim str As String
        Dim enc As New System.Text.UTF8Encoding(True)
        str = enc.GetString(bytes, 0, bytes.GetUpperBound(0))
        fs.Close()

        'split string into lines
        Dim sLines() As String
        sLines = str.Split(Environment.NewLine)

        'create table
        Dim table As New DataTable
        '*********************
        'add table columns here
        '*********************
        Dim counter As Int32
        Dim row As DataRow

        'itearte through lines
        For Each Line As String In sLines
            row = table.NewRow
            counter = 0

            'split line into columns
            Dim sCols() As String
            sCols = Line.Split("#")

            'iterate through columns
            For Each Col As String In sCols
                If Col = String.Empty Then
                    row(counter) = Convert.DBNull
                Else
                    row(counter) = Col
                End If
                counter += 1
            Next
            table.Rows.Add(row)
        Next

HTH
Ramuncikas
0
 

Author Comment

by:IvanHowarth
ID: 17116538
The first half of your code throws a complete wobbly :(

The following error message keeps recurring (regardless if it's in a try-catch statement) and can only be stopped by killing the process via task manager:

System.IO.IOException: The process cannot access the file "C:\Temp\MyTest.txt" because it is being used by another process.
  at System.IO._Error.WinIOError(Int32 errorCode, String str)
  at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize,
Boolean useAsync, String msgPath, Boolean bFormProxy)
  at System.IO.Stream..ctor(String path, FileMode mode)
  at [MyApp]

(path is a variable containing the path of the file)

Any ideas?
0
 

Author Comment

by:IvanHowarth
ID: 17116694
Disregard the above error message, I have now moved the method call as the first line to avoid any conflict.
Nevertheless, I do get the following problem:

System.ArgumentNullException: Buffer cannot be null.
Parameter name: array
  at System.IO.FileStream.Read(Byte[]array,Int32 offset, Int32 count)
  ...

Re wrote your array declaration to:

Dim bytes(CInt(fs.Length - 1)) As Byte

and then you get:

System.IndexOutOfRangeException: Cannot find column 34.
  at System.DataColumnCollection.get_Item(Int32 index)
  at System.Data.DataRow.set_Item(Int32 columnIndex, Object value)
  ...

34 columns was written to file. fs.Length gives a value of 304229
0
 

Author Comment

by:IvanHowarth
ID: 17116790
Problem found....

In my original code [AddText(fs, CType(myDRV(i), String) + "#") ] appended the # to the last column. Your code then looked for another column after this that didn't exist. I slightly modified your code so it didn't read that far:

                sCols = Line1.Split(CChar("#"))
                For y As Integer = 0 To sCols.Length - 2
                    ...
                Next
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Since .Net 2.0, Visual Basic has made it easy to create a splash screen and set it via the "Splash Screen" drop down in the Project Properties.  A splash screen set in this manner is automatically created, displayed and closed by the framework itsel…
Parsing a CSV file is a task that we are confronted with regularly, and although there are a vast number of means to do this, as a newbie, the field can be confusing and the tools can seem complex. A simple solution to parsing a customized CSV fi…
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…
This video gives you a great overview about bandwidth monitoring with SNMP and WMI with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're looking for how to monitor bandwidth using netflow or packet s…

747 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now