Click here to Skip to main content
15,885,767 members
Articles / Programming Languages / C#

Saving Files Into Database Using .NET Web Services

Rate me:
Please Sign up or sign in to vote.
4.88/5 (58 votes)
3 Oct 2010CPOL7 min read 155.8K   3.2K   113  
In this article, I will show you how to save big files into database using .NET Web Service and how to monitor transfer status.
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.IO;
using System.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Data.Sql;

namespace FileTransferWebService
{
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    public class FileTransfer : System.Web.Services.WebService
    {
        [WebMethod]
        public string GetTempFilename()
        {
            try
            {
                Guid g = Guid.NewGuid();
                //We have to create temporary file on server with unique name. 
                //In this case it will be new Guid.
                FileStream fs = new FileStream(Server.MapPath(g.ToString()), FileMode.Create);
                fs.Close();
                return g.ToString();
            }
            catch (Exception err)
            {
                throw new Exception("GetTempFilename: " + err.Message);
            }
        }

        [WebMethod]
        public void AppendToTempFile(string tempFilename, byte[] data)
        {
            try
            {
                //This method appends block of data to the end of the temporary file.
                FileStream fs = new FileStream(Server.MapPath(tempFilename), FileMode.Append);
                BinaryWriter bw = new BinaryWriter(fs);
                bw.Write(data);
                bw.Close();
                fs.Close();
            }
            catch (Exception err)
            {
                throw new Exception("AppendToTempFile: " + err.Message);
            }
        }

        [WebMethod]
        public void SaveFileIntoDatabase(string filename, string tempFilename)
        {
            SqlDatabase sqlDatabase = new SqlDatabase(ConfigurationManager.ConnectionStrings["ftConnString"].ConnectionString);
            //Now we must get all bytes from file and put them into fileData byte array.
            //This byte array we later save on database into File table.

            byte[] fileData = GetBytes(tempFilename);

            string sql = "spFile_Add";

            SqlCommand sqlCommand = sqlDatabase.GetStoredProcCommand(sql) as SqlCommand;
            try
            {
                sqlDatabase.AddInParameter(sqlCommand, "@Filename", SqlDbType.VarChar, filename);
                sqlDatabase.AddInParameter(sqlCommand, "@Content", SqlDbType.VarBinary, fileData);
                sqlDatabase.ExecuteNonQuery(sqlCommand);
            }
            catch (Exception err)
            {
                throw new Exception("SaveFileIntoDatabase: " + err.Message);
            }
        }

        public byte[] GetBytes(string path)
        {
            FileStream fs=null;
            BinaryReader br=null;
            try
            {
                byte[] buffer = null;
                fs = new FileStream(Server.MapPath(path), FileMode.Open, FileAccess.Read);
                br = new BinaryReader(fs);
                long numBytes = new FileInfo(Server.MapPath(path)).Length;
                buffer = br.ReadBytes((int)numBytes);
                br.Close();
                fs.Close();
                return buffer;
            }
            catch (Exception err)
            {
                throw new Exception("SaveFileIntoDatabase: " + err.Message);
            }
        }
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect Marwin Cassovia Soft
Slovakia Slovakia
My name is Robert Kanasz and I have been working with ASP.NET, WinForms and C# for several years.
MCSD - Web Applications
MCSE - Data Platform
MCPD - ASP.NET Developer 3.5
- Web Developer 4
MCITP - Database Administrator 2008
- Database Developer 2008
MCSA - SQL Server 2012
MCTS - .NET Framework 3.5, ASP.NET Applications
- SQL Server 2008, Database Development
- SQL Server 2008, Implementation and Maintenance
- .NET Framework 4, Data Access
- .NET Framework 4, Service Communication Applications
- .NET Framework 4, Web Applications
MS - Programming in HTML5 with JavaScript and CSS3 Specialist

Open source projects: DBScripter - Library for scripting SQL Server database objects


Please, do not forget vote

Comments and Discussions