PDA

View Full Version : Uploading Text File with OpenWriteAsync


rlcraven
08-13-2010, 02:34 PM
Hello,

My site needs to read some files, do string replacements, and save the files with a new name. To start I am trying a simple example with text files using System.Net.WebClient. The folder for input and output files is /Docs/Cust under my site root folder.

The read (using OpenReadAsync) works fine. The OpenWriteAsync does not write the file and also does not return an error. Fiddler doesn't show a problem either.

I'm using a handler in my web project and the Uri to the handler and output file name is in the call to OpenWriteAsync.

Here is the code calling OpenWriteAsync


Dim client as WebClient
Dim sFileName As String = "Modified.txt"
Dim fileContent As Byte() = System.Text.Encoding.UTF8.GetBytes(ModifiedText)

AddHandler client.OpenWriteCompleted, AddressOf Client_OpenWriteCompleted
Dim u As New Uri(Application.Current.Host.Source, "../WebServices/FileUpload.ashx/?filename=" & sFileName)
client.OpenWriteAsync(u, Nothing, fileContent)

Here's the callback from OpenWriteAsync:

Private Sub Client_OpenWriteCompleted(ByVal sender As Object, ByVal e As OpenWriteCompletedEventArgs)

Try
If e.Error IsNot Nothing Then
MessageBox.Show("OpenWriteAsync Error: " & e.Error.ToString)
End If
Dim fileContent As Byte() = TryCast(e.UserState, Byte())
Dim outputStream As Stream = e.Result
outputStream.Write(fileContent, 0, fileContent.Length)
outputStream.Close()

MessageBox.Show("Write Completed")

Catch ex As Exception
MessageBox.Show("Client_OpenWriteCompleted: " & ex.Message.ToString)
End Try

End Sub

In my webconfig I made my application full trust and also set a location tag for the destination folder as follows:


<location path="Cust">
<system.webServer>
<security>
<authorization>
<add accessType="Allow" users="*" />
</authorization>
</security>
</system.webServer>
</location>

Obviously I don't want to use the "*" except for testing purposes.

If anyone has a suggestion concerning why the output file doesn't get created, that would be most appreciated!

Randy

rlcraven
08-15-2010, 02:20 PM
Solved it...

The code uses a generic handler (FileUplod.ashx) that implements IHttpHandler. This requires an IsReusable property and a ProcessRequest method.

In VB.NET the the procedure and property must also have an implements keyword:

Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest

I guess that in C# adding implements to the class definition is enough.

Anyway, its working...

mjp
08-16-2010, 01:48 PM
Glad it's working for you, thanks for the follow-up.