Bobj-C
Bobj-C

Reputation: 5426

Error Stream was not readble

I wrote the code below and I got an error (Stream was not readble) while execute this line SR = New StreamReader(FS) why and how to fix it

the code :

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim FS As FileStream
    Dim SR As StreamReader
    Dim SW As StreamWriter
    Dim FS_Out As FileStream
    FS = New FileStream("C:\Temp\My Picture.JPG", System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write)
    SR = New StreamReader(FS)
    FS_Out = New FileStream("C:\Temp\My Picture Out.JPG", FileMode.Create, FileAccess.ReadWrite)
    SW = New StreamWriter(FS_Out)

    Dim alltext As String
    FS.Seek(0, SeekOrigin.Begin)
    alltext = SR.ReadToEnd()

    'SW.Write (Buffer)



    SR.Close()
    FS.Close()


End Sub

Upvotes: 2

Views: 868

Answers (3)

Marc Gravell
Marc Gravell

Reputation: 1062915

You open FS with only the "write" flag, then try to read from it. Personally I always use File.OpenRead, File.OpenWrite, etc - much easier and clearer.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500835

Well look at what you've asked for:

FS = New FileStream("C:\Temp\My Picture.JPG", _
                    FileMode.OpenOrCreate, FileAccess.Write)

You've asked to open or create a file for writing. Nothing about reading.

Now, on top of that, you're trying to use StreamReader and StreamWriter for jpeg files. Don't do that. Pictures are binary files; TextReader and TextWriter (and the subclasses) are for text files. What would the string representation of a picture look like?

Next, you ought to use "Using" statements to make sure you close your streams/readers/writers even if an exception occurs.

Next, most of the time it's simplest to use the static methods of the File class to open streams or readers for files. That way, the method you use says what you want to do with the stream - e.g. File.OpenRead, File.OpenWrite, File.ReadAllText etc.

Next, if you really want to copy the file, you can use File.Copy. If you want to read all the data into memory and copy it, you can use File.ReadAllBytes and File.WriteAllBytes which means you don't need to mess around with the streams yourself at all.

Upvotes: 2

Felice Pollano
Felice Pollano

Reputation: 33252

It appear you mismatch the mode on FS, it should be FileAccess.ReadWrite.

Upvotes: 0

Related Questions