我使用这种方法将文件上传到ftp:
public FtpUploader()
{
try
{
State state = new State();
state.request = (FtpWebRequest)FtpWebRequest.Create(
ftpurl + "/" + Path.GetFileName(filename));
state.request.Method = WebRequestMethods.Ftp.UploadFile;
state.request.Credentials = new NetworkCredential(ftpusername, ftppassword);
state.sourceStream = new StreamReader(filename);
state.request.BeginGetRequestStream(new AsyncCallback(ConnectCallback), state);
connectDone.WaitOne();
state.fileContents = Encoding.UTF8.GetBytes(state.sourceStream.ReadToEnd());
state.sourceStream.Close();
Send(state);
sendDone.WaitOne();
state.requestStream.Close();
Receive(state);
receiveDone.WaitOne();
Console.WriteLine("Upload File Complete, status {0}", state.stringResponse);
state.response.Close();
}
catch (Exception err)
{
string t = err.ToString();
}
}
当它走到界限时:
Send(state);
然后它跳转到Send方法并尝试在内部执行该行:
private static void Send(State state)
{
state.request.BeginGetRequestStream(new AsyncCallback(SendCallback), state);
}
当它尝试执行此行时,它会跳回到捕获区域的FtpUploader方法并抛出异常:
InvalidOperationException异常:
在前一个通话仍在进行中时,无法重新调用BeginGetRequestStream / BeginGetResponse
System.InvalidOperationException was caught
HResult=-2146233079
Message=Cannot re-call BeginGetRequestStream/BeginGetResponse while a previous call is still in progress.
Source=System
StackTrace:
at System.Net.FtpWebRequest.BeginGetRequestStream(AsyncCallback callback, Object state)
at mws.FtpUploader.Send(State state) in FtpUploader.cs:line 151
at mws.FtpUploader..ctor() in FtpUploader.cs:line 63
InnerException:
第151行是:
state.request.BeginGetRequestStream(new AsyncCallback(SendCallback), state);
第63行是:
Send(state);