My requirement was to send the file through the mail and save the file in binary format.
Issue faced
File content length became 0 after converted to the byte array.
Solution
1) Created a class with properties
public class Model_File
{
public string FileName { get;private set; }
public string ContentType { get; private set; }
public byte[] Contents { get; private set; }
public Model_File(string FileName, string ContentType, byte[] Contents)
{
this.FileName = FileName;
this.ContentType = ContentType;
this.Contents = Contents;
}
}
2) Read all the file using binary reader and store in a List of class
public static List<Model_File> Get_File(HttpPostedFileBase[] postedfiles)
{
var Result =new List<Model.Model_File>();
if (postedfiles.Length != 0)
{
foreach (var item in postedfiles)
{
if (item.ContentLength != 0)
{
var R = Try_Byte(item, "Attachment");
if (R != null)
{
Result .Add(R);
}
}
}
}
return Result;
}
private static Model_File Try_Byte(HttpPostedFileBase F,string CType)
{
Model.Model_File Result = null;
if (F != null && F.ContentLength!=0)
{
using (BinaryReader dr = new BinaryReader(F.InputStream))
{
byte[] content = dr.ReadBytes(F.ContentLength);
return new Model_File(F.FileName, CType, content);
}
}
return Result;
}
3) To Send these files in mail - Create the attachment and add to the mail message
public static void Send(List<Model_File> _Files)
{
MailMessage msg = new MailMessage()
if(_Files.count!=0)
{
_Files.foreach(delegate(Model_File F){
var _Attachment=Get(F)
if(_Attachment!=mull){
msg.Attachments.Add(_Attachment);
}
});
}
}
private static Attachment Get(Model_File F)
{
if (F != null && F.Contents!=null && F.Contents.Length!=0 && !string.IsNullOrWhiteSpace(F.ContentType))
{
return new Attachment(new MemoryStream(F.Contents), F.FName);
}
return null;
}
4) Get the result- List of Model_Files objects and inserted to the database in varbinary format.For that I created the column in table with an attribute varbinary(max).
*Issue *
Cant covert to varbinary to varchar - this error got when added like a normal parameter.
Solution
Then i declared the parameter as below.
Command.Parameters.Add("@Attachment", System.Data.SqlDbType.VarBinary, -1).Value = (A.Contents == null ? (object)DBNull.Value : (object)A.Contents );
Top comments (4)
Why is your post tagged #c? This isn't C code.
NO, This is C# Code which i used in one of my MVC project.
Then it should be tagged #csharp. #c is for the C programming language..
Done.