通过Web服务上传文件:不支持给定的文件路径格式

时间:2013-02-15 00:12:52

标签: c# file upload asmx

我正在尝试使用网络服务将文件上传到网络服务器。问题是,每当我尝试使用引用的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();
}
}

我做错了什么?

编辑:我改变了我的网络服务代码,看起来像这样

    [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();

这样我就不会得到任何例外,但文件仍然没有创建,我在我的网站上找到了“ciao.txt”而无法找到它。

任何帮助?

edit2:解决了!我将我的网站设置在框架4.0 - 4.5上,而我的程序是在框架3.5下编译的,只要我切换它运行的框架。

2 个答案:

答案 0 :(得分:0)

这篇文章我发现有助于从网站将文件加载到数据库中:

http://www.codeproject.com/Articles/48619/Reading-and-Writing-BLOB-Data-to-Microsoft-SQL-or

答案 1 :(得分:0)

您的问题可能与此类似,已经回答:

"The given path's format is not supported."