I am trying to upload files to a web server using a web service. The problem is that I get a "given file format not supported" exception every time I try use the referenced web method.
This is the code inside my application:
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();
And this is the code inside http://MySite.somee.com/WebServices/WebService1/upload.asmx.cs (my site is not actually called 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();
}
}
What am I doing wrong?
edit: i changed my web service code to look like this
[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();
}
and updated my client accordingly
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();
this way i don' t get any exceptions but the file still isn' t created, i looked for "ciao.txt" all over my site and couldnt find it.
Any help ?
edit2: solved ! i had my site set on framework 4.0 - 4.5 while my program was compiled under framework 3.5, as soon as i switched the framework it worked.