2012-10-09 56 views
0

的问题是相当简单的,而且有些无意义我理解,但仍...如何从数据库文件保存到服务器

数据库在服务器上,当然,我需要将启动时的动作从数据库中抓取该文件并将其保存到我的AppSettings["Active"]配置属性中的文件夹。

基本上,

public ActionResult Activate(int id) 
{ 
    Project project = db.Projects.Find(id); 

    var activeProjectData = project.XML; // project.XML returns byte[] type 
    //For download (not in this method of course) i'm using something like return File(activeProjectData, "text/xml"); and that works ok 

} 

现在我想的是文件保存到AppSettings["Active"]路径。不确定如何去做。我尝试过使用System.IO.File.Create(),但那个效果并不好。

任何帮助表示赞赏。

+0

文件从数据库中?你的意思是文件以二进制形式存储在数据库中? –

+0

是的,文件在数据库中是二进制的。 – rexdefuror

回答

3

只需创建一个FileStream,并用它来写数据:

string fileName = ConfigurationManager.AppSettings["Active"]; 
using(var fs = new FileStream(fileName, FileMode.Create, FileAccess.Write)) 
{ 
    fs.Write(project.XML, 0, project.XML.Length); 
} 

如果没有需要更多的控制,还有对Filesimple helper method

File.WriteAllBytes(fileName, project.XML); 
+0

这看起来很有前途,我知道它是'File'类的东西......只是不能把它当成现货。将尝试它,谢谢。 – rexdefuror

+0

我会使用'File.OpenWrite(fileName)'而不是手动创建FileStream,它基本上只是包装'新的FileStream',但它看起来更干净。 :) – Patrick

+0

我用'File.WriteAllBytes()'像一个魅力工作,仍然看起来干净:)感谢driis! – rexdefuror

0

您需要使用FileStream

SqlCommand ("select fileBin from SomeTable", connection); 
byte[] buffer = (byte[]) command.ExecuteScalar(); 
connection.Close(); 
FileStream fs = new FileStream(@"C:\filename.pdf", FileMode.Create); 
fs.Write(buffer, 0, buffer.Length); 
fs.Close(); 
相关问题