开发者

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 FileS开发者_StackOverflowtream("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


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.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜