Any Alternatives to StreamReader and File Classes?


DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

Results 1 to 6 of 6

Thread: Any Alternatives to StreamReader and File Classes?

  1. #1
    Join Date
    Dec 2008
    Location
    *****, Nigeria
    Posts
    62

    Any Alternatives to StreamReader and File Classes?

    Hi,

    I need to access a csv file in my silverlight app. and read it line by line into a string array. I keep coming up with this error: Unable to Access method StreamReader...ctor. The code below worked perfectly in VS 2008 but i'm stuck with VS2010 and its not working. I also noticed some functions in File namespace like ReadAllLines are no more accessible in VS2010! I've used intellisense to look for alternatives all to no avail. So could any one out there help out PLEASE! I've got a deadline for tomorrow. THANKS
    Code:
    Using reader = New StreamReader("C:\HierarchicalDef.csv")...
     Dim books = _
          From line In File.ReadAllLines("books.csv") _
          Where Not line.StartsWith("#") _
          Let parts = line.Split(",") _
          Select New With {.Isbn = parts(0), .Title = parts(1), .Publisher = parts(3)}
    Mobile: +234 706 042 6036
    Email: charles@hedonmark.com
    Website: www.hedonmark.com

    “To be yourself in a world that is constantly trying to make you something else is the greatest accomplishment.”
    —Ralph Waldo Emerson

  2. #2
    Join Date
    Feb 2004
    Location
    Longueuil, Québec
    Posts
    577
    First of all, a deadline with a Beta version ??? Unless you are a MSDN subscriber and are very quick on the download, that is what you are using, since the Release candidate has been released only yesterday, and only to MSDN subscribers.

    You can expect strange problems like that with beta versions.

    Since the code you sent us is only an excerpt of the original, it is not functionnal, but I tried the equivalent in the 10.0.21006.1 B2 Rel build of Visual Studio 2010 Ultimate:

    Code:
    Using reader = New System.IO.StreamReader("C:\HierarchicalDef.csv")
       'Work with the reader
    End Using
    
    Dim S As String()
    S = System.IO.File.ReadAllLines("C:\HierarchicalDef.csv")
    Both worked just as expected.

    The method ctor is the constructor. Since you cannot instantiate the StreamReader, I suspect that your installation of Visual Studios is corrupted, or that your version of the Beta is older than mine and not ready for prime time. Try reinstalling it, download the newer Beta, or wait until tomorrow (the 10th), when the Release Candidate will be widely available. The Release Candidate is the closest you can get to the final version.

    As for the ReadAllLine, what is the error message? Are you sure that the problem comes from the File class?

    You are using LINQ, and LINQ is known to sometimes behave in strange ways. Although it was heralded as THE biggest new feature of Visual Studio 2008, and although the basic idea was good, most serious programmers I know (and as a VB trainer I meet a couple hundred a year) have scrapped it for a lot of reasons, including strange hard to pinpoint bugs. Looking in the "What's New" of Visual Studio 2010, there is nothing new about LINQ, which is strange, since it was so prominent in the marketing on Visual 2008. This, for me, is a hidden confirmation from Microsoft that they went wrong with something that was a good idea but was not implemented properly.

    Your problem might come from LINQ while you think that it comes from the File class.

    Not pertinent to your problem, but in my opinion, about LINQ:

    Give yourself a gift. Refrain from using LINQ. In order to save 10 or 20 minutes of coding by using LINQ, you often end up losing many hours trying to understand why it does not work as intended.

    Loop through the lines in a For loop, and extract those that do not start in #. That is what the From does anyway. 3 lines with the For is not a high price to pay in exchange of a LINQ From that does not do what you want.
    Jacques Bourgeois
    JBFI
    http://www3.sympatico.ca/jbfi/homeus.htm

  3. #3
    Join Date
    Dec 2008
    Location
    *****, Nigeria
    Posts
    62
    Hi JBourgeois,
    Thanks for the reply. I have not acquired the Release Candidate yet, but i tried the imperative style alternative to LINQ(declarative) and i had a browser that didnt display anything as if the Initializecomponent() method didnt even run. As for the File.ReadAllLines() when i type File and dot the intellisense options dont include ReadAllLines in the drop down combo that appears after the dot.

    Let me just summarize what the project is about:
    I have a Silverlight RadTreeView Hierarchical Control sitting on a xaml page (Just 1 TreeView item on it rep. the highest level in the org.) and a button below it that reads a text file into an object in RAM and then calls a recursive function which dynamically creates new nodes and sets their header texts or captions until the TreeView is fully built. Thereby building an organogram or organizational hierarchy chart kind of. The Code behind is posted below.

    However, i was reminded of the fact that Silverlight has a Sandbox model and that the framework won't let users ofthe application to read or write to files directly on the hard drive (C:\) or any other storage for that matter. so i read up Isolated storage and applied what i had read to no avail. I strongly agree with you that the beta version i'm using is pretty buggy. Can you imagine I can't even step through my code to debug it?

    For now, the version of the code that uses LINQ allows the page load and display the button(btnDrawChart) and a third party Telerik RadTreeView Control but the one that uses the imperative style i.e For Each doesn't show anythingafter the page has loaded. Both of them are below:

    Code:
    Imports System.IO
    Imports System.Linq.Expressions
    Imports Telerik.Windows.Controls
    Imports System.IO.IsolatedStorage
    Partial Public Class MainPage
        Inherits UserControl
    
        Public Sub New()
            InitializeComponent()
            Using store = IsolatedStorageFile.GetUserStoreForApplication()
                Using stream = store.CreateFile("OrganogramFile.txt")
                    Using writer = New StreamWriter(stream)
                        writer.WriteLine("#FIELD DEFINITION:item_id, header, parent, hasChild")
                        writer.WriteLine("1,CEO,0,1")
                        writer.WriteLine("2,ED1,1,1")
                        writer.WriteLine("3,ED2,1,1")
                        writer.WriteLine("4,ED3,1,1")
                        writer.WriteLine("5,DL1,2,0")
                        writer.WriteLine("6,DL2,2,0")
                        writer.WriteLine("7,DL3,3,0")
                        writer.WriteLine("8,DL4,4,0")
                    End Using
                End Using
            End Using
        End Sub
    
        Private Sub btnDrawChart_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnDrawChart.Click
            Using store = IsolatedStorageFile.GetUserStoreForApplication()
                Using stream = store.OpenFile("OrganogramFile.txt", FileMode.Open)
                    Using reader = New StreamReader(stream)
                        Dim oneline As String
                        Dim line_array As String = String.Empty
                        oneline = reader.ReadLine
                        Do Until oneline.Equals("")
                            line_array += oneline
                            line_array += " "
                            oneline = reader.ReadLine
                        Loop
                        Dim items = _
                        From line In line_array.Split(" ") _
                        Where Not line.StartsWith("#") _
                        Let parts = line.Split(",") _
                        Select New treeViewElement With {.item_id = parts(0), .header = parts(1), .parent = parts(2), .hasChild = parts(3)}
    
                        attachChild(Me.RadTreeViewItem1, items, "0")
                    End Using
                End Using
            End Using
    
    Private Sub attachChild(ByRef parentTreeview As RadTreeViewItem, ByRef items As List(Of treeViewElement), ByRef parent_id As String)
            For Each treeviewitem As treeViewElement In items
                Dim treeviewchild As New RadTreeViewItem
                If treeviewitem.parent.ToString = parent_id Then
                    treeviewchild.Header = treeviewitem.header
                    parentTreeview.Items.Add(treeviewchild)
                End If
                If treeviewitem.hasChild = "1" Then
                    attachChild(treeviewchild, items, treeviewitem.item_id)
                End If
            Next
        End Sub
    
    End Class
    Imperative Style Using For Each Is below:
    Code:
    Imports System.IO
    Imports System.Linq.Expressions
    Imports Telerik.Windows.Controls
    Partial Public Class MainPage
        Inherits UserControl
    
        Public Sub New()
            InitializeComponent()
        End Sub
    
        Private Sub btnDrawChart_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnDrawChart.Click
            Dim openFile As New OpenFileDialog
            openFile.ShowDialog()
            If openFile.File.Equals(Nothing) Then Exit Sub
            Dim filename As String = openFile.File.FullName
            Using reader = New StreamReader(filename)
                Dim oneline As String
                Dim line_array As String = String.Empty
                oneline = reader.ReadLine
                Do Until oneline.Equals("")
                    line_array += oneline
                    line_array += " "
                    oneline = reader.ReadLine
                Loop
                'Dim items = _
                'From line In line_array.Split(" ") _
                'Where Not line.StartsWith("#") _
                'Let parts = line.Split(",") _
                'Select New treeViewElement With {.item_id = parts(0), .header = parts(1), .parent = parts(2), .hasChild = parts(3)}
    
    
                Dim treeviewitemList As List(Of treeViewElement) = New List(Of treeViewElement)
                For Each line As String In line_array.Split(" ")
                    If line.StartsWith("#") Then Continue For
                    Dim parts As String() = line.Split(",")
                    Dim treeviewitem As treeViewElement = New treeViewElement
    
                    treeviewitem.item_id = parts(0)
                    treeviewitem.header = parts(1)
                    treeviewitem.parent = parts(2)
                    treeviewitem.hasChild = parts(3)
                    treeviewitemList.Add(treeviewitem)
                Next
    
                attachChild(Me.RadTreeViewItem1, treeviewitemList, "0")
    End Using
    
    
    
        End Sub
        Private Sub attachChild(ByRef parentTreeview As RadTreeViewItem, ByRef items As List(Of treeViewElement), ByRef parent_id As String)
            For Each treeviewitem As treeViewElement In items
                Dim treeviewchild As New RadTreeViewItem
                If treeviewitem.parent.ToString = parent_id Then
                    treeviewchild.Header = treeviewitem.header
                    parentTreeview.Items.Add(treeviewchild)
                End If
                If treeviewitem.hasChild = "1" Then
                    attachChild(treeviewchild, items, treeviewitem.item_id)
                End If
            Next
        End Sub
    
    End Class
    For the Records here's the error that displays when i run the LINQ version:

    An Unhandled exception("unhandled error in Silverlight Application Code:4004
    Category:ManagedRuntimeError
    Message:System.MethodAccessException:Attempt to access the method failed: System.IO.StreamReader..ctor(System.String). Like i earlier said i dont get this error when i run the imperative For Each version as nothing displays on the web page.
    Sorry if i bored you with the details in any way. Thanks for the patience
    nonetheless.

    Regards,

    Charles.
    Mobile: +234 706 042 6036
    Email: charles@hedonmark.com
    Website: www.hedonmark.com

    “To be yourself in a world that is constantly trying to make you something else is the greatest accomplishment.”
    —Ralph Waldo Emerson

  4. #4
    Join Date
    Feb 2004
    Location
    Longueuil, Québec
    Posts
    577
    Hi Charles.

    The Release Candidate has been made available yesterday to everyone. A few people complained to me today that the site was so busy that they were not able to get it, but being a lucky guy, I had not problem getting my copy.

    Might solve your problem.

    You can try from the Canadian site, which is sometimes faster than the US site when a heavily waited for piece of software becomes available: http://msdn.microsoft.com/en-ca/vstudio/dd582936.aspx.

    ----

    Also, I had not noted the "Silverlight" at the beginning of your original post. Since I do not use Silverlight, there might be issues that I am not familiar with in that environment.

    For one, Silverlight applications usually come from the Web or the Intranet, and FileIOPermissionAccess.Read is needed to use File.ReadAllLines. There are reasons to think that this method is not available from Silverlight. And since you seem to imply that you work in a Sandbox model, it is quite possible that the Sandbox hides unavailable methods to you. Only presumptions however, I know nothing of Silverlight outside of a few demos presented at Microsoft events.

    ----

    And although I do not program in Silverlight and dislike LINQ, you do not bore me with your details. Not at all.

    First, they might help others help you.

    Second, people who attends my "Introduction to VB.NET" classes have different needs, and a few of them will have needs for those technologies. In order to get better at my work of introducing them to VB, it is always useful for me to learn about real life experiences feedback in domains I am not know very well.

    ----

    Good luck with your project
    Jacques Bourgeois
    JBFI
    http://www3.sympatico.ca/jbfi/homeus.htm

  5. #5
    Join Date
    Dec 2008
    Location
    *****, Nigeria
    Posts
    62
    Halo JB,

    Hope your weekend was great. Indeed it was the SAndbox model of SL that was causing all the hassles. I got around the problem. Today, the TRee View finally displayed on the web page, though it still needs a little tweaking here and there . At least its nowthe logic errors not syntax errors that are left even though that on its own could be troublesome atimes! Well here's a snippet i found in an ebook:
    Code:
    try
    {
    using (IsolatedStorageFile store =
    IsolatedStorageFile.GetUserStoreForApplication())
    {
    using (IsolatedStorageFileStream stream = store.CreateFile("date.txt"))
    {
    StreamWriter writer = new StreamWriter(stream);
    writer.Write(DateTime.Now);
    writer.Close();
    }
    lblStatus.Text = "Data written to date.txt";
    }
    }
    catch (Exception err)
    {
    lblStatus.Text = err.Message;
    }
    Retrieving information is just as easy. You simply need to open the
    IsolatedStorageFileStream object in read mode:
    // Read from isolated storage.
    try
    {
    using (IsolatedStorageFile store =
    IsolatedStorageFile.GetUserStoreForApplication())
    {
    using (IsolatedStorageFileStream stream = store.OpenFile("date.txt",
    FileMode.Open))
    {
    StreamReader reader = new StreamReader(stream);
    lblData.Text = reader.ReadLine();
    reader.Close();
    }
    }
    }
    catch (Exception err)
    {
    // An exception will occur if you attempt to open a file that doesn't exist.
    lblStatus.Text = err.Message;
    }
    Thoughits CSharp i have since converted it to VB.NET. Thanks for all the help and links. Indeed a problem shared is half solved. THanks again.

    Charles.
    Mobile: +234 706 042 6036
    Email: charles@hedonmark.com
    Website: www.hedonmark.com

    “To be yourself in a world that is constantly trying to make you something else is the greatest accomplishment.”
    —Ralph Waldo Emerson

  6. #6
    Join Date
    Feb 2004
    Location
    Longueuil, Québec
    Posts
    577
    Quote Originally Posted by proffy View Post
    Though its CSharp i have since converted it to VB.NET.
    Good example that should be followed by everybody, either from C# to VB or the reverse.

    We are all working with the same environment, the same classes and methods. Sometimes, you find the answer to your VB problems in a C# piece of code.

    Too many programmers in one language disregard anything that is done in the other. Only the syntax differs. The basics of what needs to be done in one language are the same as in the other one.
    Jacques Bourgeois
    JBFI
    http://www3.sympatico.ca/jbfi/homeus.htm

Similar Threads

  1. Replies: 2
    Last Post: 11-30-2009, 08:33 AM
  2. VB.Net streamreader / streamwriter
    By leannan in forum .NET
    Replies: 12
    Last Post: 01-27-2009, 06:23 PM
  3. Replies: 4
    Last Post: 03-14-2007, 09:27 AM
  4. Replies: 6
    Last Post: 08-16-2006, 11:32 PM
  5. Text file into XML(Urgent)
    By selvakumar_82 in forum ASP.NET
    Replies: 0
    Last Post: 07-24-2006, 01:14 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center
 
 
FAQ
Latest Articles
Java
.NET
XML
Database
Enterprise
Questions? Contact us.
C++
Web Development
Wireless
Latest Tips
Open Source


   Development Centers

   -- Android Development Center
   -- Cloud Development Project Center
   -- HTML5 Development Center
   -- Windows Mobile Development Center