Solved

StreamWriter - .Write or .WriteLine - a discrepancy?

Posted on 2006-11-17
7
1,089 Views
Last Modified: 2008-01-09
The background to this question is here

http://www.experts-exchange.com/Programming/Programming_Languages/Dot_Net/VB_DOT_NET/Q_22058379.html

It explains - if any explanation is needed - why the task that is simplified in the code below might be carried out "for real".

This is VB.NET 2005.  

A test file with these contents

1;Adam
2;Bill
3;Chris
4;Dave

saved in my case as "C:\Test\TestFile.txt".  If you try this and change the path/name, you will need to change the references in both Button_Click subs below.

One form with two buttons on and one datagridview (called DGV).  This code

Imports System.IO
Imports System.Data.OleDb

Public Class frmTest

    Private Sub makeSchemaWithWrite(ByVal thePath As String, ByVal theFile As String, ByVal delimiter As Char, ByVal headers As Boolean)

        Dim thisFile As String = thePath & "\schema.ini"

        'Ensure any existing schema ini file is deleted
        If My.Computer.FileSystem.FileExists(thisFile) Then
            My.Computer.FileSystem.DeleteFile(thisFile)
        End If

        Dim f As New StreamWriter(thisFile)
        Dim t As String = "[" & theFile & "]" & vbCrLf
        t &= "Format=Delimited(;)" & vbCrLf
        t &= "ColNameHeader = " & headers & vbCrLf
        t &= "CharacterSet=ANSI" & vbCrLf
        t &= "col1=ID Integer" & vbCrLf
        t &= "col2=Name char width 10" & vbCrLf
        f.Write(t)

        f.Close()
        f.Dispose()

    End Sub

    Private Sub makeSchemaWithWriteLine(ByVal thePath As String, ByVal theFile As String, ByVal delimiter As Char, ByVal headers As Boolean)

        Dim thisFile As String = thePath & "\schema.ini"

        'Ensure any existing schema ini file is deleted
        If My.Computer.FileSystem.FileExists(thisFile) Then
            My.Computer.FileSystem.DeleteFile(thisFile)
        End If

        Dim f As StreamWriter
        f = My.Computer.FileSystem.OpenTextFileWriter(thisFile, False)
        f.WriteLine("[" & theFile & "]")
        f.WriteLine("Format=Delimited(;)")
        f.WriteLine("ColNameHeader = " & headers)
        f.WriteLine("CharacterSet=ANSI")
        f.WriteLine("col1=ID Integer")
        f.WriteLine("col2=Name char width 10")

        f.Close()
        f.Dispose()

    End Sub

    Private Sub LoadData(ByVal fname As String, ByVal useLines As Boolean)

        If Not My.Computer.FileSystem.FileExists(fname) Then Exit Sub

        Dim fiMyFile As FileInfo = New FileInfo(fname)

        Dim thisPath As String = fiMyFile.DirectoryName
        Dim sourceFile As String = fiMyFile.Name

        If useLines Then
            makeSchemaWithWriteLine(thisPath, sourceFile, ";", False)
        Else
            makeSchemaWithWrite(thisPath, sourceFile, ";", False)
        End If

        Dim sConnectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;" & "Data Source=" & thisPath & ";Extended Properties=""Text"";"
        Dim cConn As New OleDbConnection(sConnectionString)

        Dim sSQL As String = "SELECT * FROM " & sourceFile & " WHERE ID > 2"
        Dim da As New OleDbDataAdapter(sSQL, cConn)

        Dim dt As New DataTable

        Try
            da.Fill(dt)
            DGV.DataSource = dt
        Catch ex As Exception
            MsgBox(ex.Message)
            DGV.DataSource = Nothing
        End Try

    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        LoadData("C:\Test\TestFile.txt", True)
    End Sub

    Private Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button2.Click
        LoadData("C:\Test\TestFile.txt", False)
    End Sub

End Class

The purpose of the program is to read the test file's contents, which are semicolon-delmited, using the Jet.OleDB Text engine and a schema.ini, into a datatable, hence datagridview.  The schema.ini is written on the fly.  Two methods of writing it are used.  MessageBox code is included to show that in both cases the schema.ini file has been written.  But when it gets to using that file, one works OK: the other doesn't.

My question is, why?

Roger
0
Comment
Question by:Sancler
  • 4
  • 3
7 Comments
 
LVL 34

Author Comment

by:Sancler
ID: 17965839
Oops, I missed the message box code out

        Dim sr As New StreamReader(thisPath & "\schema.ini")
        MsgBox(sr.ReadToEnd)
        sr.Close()

should go immediately after

        If useLines Then
            makeSchemaWithWriteLine(thisPath, sourceFile, ";", False)
        Else
            makeSchemaWithWrite(thisPath, sourceFile, ";", False)
        End If

in the LoadData sub

Roger
0
 
LVL 85

Accepted Solution

by:
Mike Tomlinson earned 500 total points
ID: 17965961
Hey Roger,

The two methods of opening up a StreamWriter use different default encoding schemes...

The first:

    Dim f As New StreamWriter(thisFile)

Uses "UTF-8 encoding without a Byte-Order Mark (BOM)".
See:
http://msdn2.microsoft.com/en-us/library/fysy0a4b.aspx

The second:

    Dim f As StreamWriter
    f = My.Computer.FileSystem.OpenTextFileWriter(thisFile, False)

Uses Ascii encoding.
See:
http://msdn2.microsoft.com/en-us/library/bb830kfe.aspx

So try using the SAME method of creating the StreamWriters and see if that makes a difference.

~IM
0
 
LVL 34

Author Comment

by:Sancler
ID: 17966066
Mike

Thanks.  I wondered about that and reckoned to check - not with the msdn docs, but by examining the files at byte level.  But, I have to admit, it was quite late and I probably put a wrong file through the loop.  I'll have a crack at it again with that in mind.  But I'm on something else now, so it'll be a few hours.  Watch this space.

Roger
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 17967383
Roger,

So others can benefit as well...

Which one works?

    (A) "UTF-8 encoding without a Byte-Order Mark (BOM)"
          via New StreamWriter(thisFile)

    (B) ASCII
         via My.Computer.FileSystem.OpenTextFileWriter(thisFile, False)
0
 
LVL 34

Author Comment

by:Sancler
ID: 17967394
Mike

That's it.  I re-tried my byte-reads and got the BOM on the one that didn't work but not on the other.  Anyway, although the actual problem was resolved at the time, it's nice now to know quite why.

Thanks

Roger
0
 
LVL 34

Author Comment

by:Sancler
ID: 17967415
Cross post.  Just for clarification.  fFor this purpose we MUST use New StreamWriter(thisFile) and NOT My.Computer.FileSystem.OpenTextFileWriter(thisFile, False)

Roger
0
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 17967446
=)
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Protecting vb6 & .Net code Obfuscation 18 96
Getting multiple values from a dataset ASP.NET(VB) 3 37
VB.Net How to Exit Sub - Exit Form??? 5 51
Help with Syntax 9 28
If you're writing a .NET application to connect to an Access .mdb database and use pre-existing queries that require parameters, you've come to the right place! Let's say the pre-existing query(qryCust) in Access takes a Date as a parameter and l…
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…
Internet Business Fax to Email Made Easy - With  eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, f…
Many functions in Excel can make decisions. The most simple of these is the IF function: it returns a value depending on whether a condition you describe is true or false. Once you get the hang of using the IF function, you will find it easier to us…

920 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

17 Experts available now in Live!

Get 1:1 Help Now