我試圖使用Web服務將文件上傳到Web服務器。問題是我每次嘗試使用引用的Web方法時都會收到「不支持的給定文件格式」異常。通過Web服務上傳文件:不支持給定的文件路徑格式
這是我的應用程序中的代碼:
Service1 upload = new Service1();
FileStream fs = new FileStream("ciao.txt", FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
BinaryReader br = new BinaryReader(fs);
int length = new FileInfo("ciao.txt").Length;
byte[] buffer = br.ReadBytes((Int32)length);
upload.WriteFile(buffer, "ciao.txt"); // <-- Exception
br.Close();
fs.Close();
而且這裏面http://MySite.somee.com/WebServices/WebService1/upload.asmx.cs代碼(我的網站實際上沒有所謂的MySite)
[WebService(Namespace = "http://MySite.somee.com/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
public class Service1 : System.Web.Services.WebService
{
[WebMethod]
public void WriteFile(byte[] buffer, string FileName)
{
StreamWriter sw = new StreamWriter(FileName, false);
sw.Write(buffer.ToString());
sw.Close();
}
}
我在做什麼錯?
編輯:我改變了我的web服務代碼看起來像這樣
[WebMethod]
public void UploadFile(byte[] f, string fileName)
{
MemoryStream ms = new MemoryStream(f);
FileStream fs = new FileStream(Path.Combine(System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath, "/ciao.txt");, FileMode.Create)
ms.WriteTo(fs);
ms.Close();
fs.Close();
fs.Dispose();
}
並更新了相應
FileInfo fInfo = new FileInfo("ciao.txt");
FileStream fStream = new FileStream("ciao.txt", FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fStream);
long numBytes = fInfo.Length;
byte[] data = br.ReadBytes((int)numBytes);
br.Close();
MyService.UploadFile(data, "ciao.txt");
fStream.Close();
fStream.Dispose();
客戶端這樣我不得到任何異常,但文件仍ISN「 t創建後,我在我的網站上查找「ciao.txt」,並找不到它。
任何幫助?
edit2:解決了!一旦我切換了它的工作框架,我的網站就設置在框架4.0 - 4.5上,而我的程序在框架3.5下編譯。
等待,什麼字符串? – user1909612 2013-02-15 00:17:05
你試過調試過嗎? 'StreamWriter'構造函數之前'FileName'的價值是什麼?另外,'StreamWriter'寫入字符串,並且你傳遞字節。你需要直接嘗試'FileStream'。 – 2013-02-15 00:18:09
問題是我沒有在本地運行,它託管在某個虛擬服務器上,我只能調試客戶端應用程序。 @CSharp學生是我知道,我的意思是什麼字符串應該使用@?文件名 ? – user1909612 2013-02-15 00:21:00