분노의 챔질

C# File to ByteArray 본문

Programming/C#

C# File to ByteArray

분노의블로그 2010. 2. 23. 10:30
반응형

using System.Windows.Forms;
using System.IO;
using System;
using System.Diagnostics;

namespace FileToByteTest
{
    public partial class Filetest : Form
    {

        Byte[] FileByte;
        public Filetest()
        {
            InitializeComponent();

            this.txtFilePath.ButtonClick += (sender, e) =>
                {
                    FileDialog dialog = new OpenFileDialog();
                    string EducationFilePath = string.Empty;
                    if (dialog.ShowDialog() == DialogResult.OK)
                    {
                        EducationFilePath = dialog.FileName;
                        this.txtFilePath.EditText = EducationFilePath;

                    }
                    string[] strFileName = EducationFilePath.Split("\\".ToCharArray());
                    this.txtFileName.Text = strFileName[strFileName.Length - 1];
                    FileByte = FileToByteArray(EducationFilePath);
                };

 

            this.button1.Click += (sender, e) =>
                {
                    //다른곳에 저장하려면 SaveFileDialog사용하여 경로설정하자
                    var path = @"D:\TEMP\";
                    string FileName = this.txtFileName.Text;
                    if (FileName != string.Empty)
                    {
                        int ArraySize = FileByte.Length;
                        FileStream fs = new FileStream(path + FileName, FileMode.OpenOrCreate, FileAccess.Write);
                        fs.Write(FileByte, 0, ArraySize);
                        fs.Close();
                       
                        //파일을 자동으로 실행시 사용.. 아니면 지우자
                        Process p = new Process();
                        p.StartInfo.FileName = path + FileName;
                        p.Start();
                    }
                };
        }

        

        private byte[] FileToByteArray(string filePath)
        {
            using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
            {
                int length = Convert.ToInt32(fs.Length);
                BinaryReader br = new BinaryReader(fs);
                byte[] buff = br.ReadBytes(length);
                fs.Close();

                return buff;
            }
        }

    }
}

 

특정파일을 Byte[]로 변환한뒤 변환된 Byte[]를 File로 변환하여 실행...

 

첨부파일로 사용하면 된다... MSSQL에 필드 2개를 잡자

FileName navarchar(100)

AttachedFile varbinary(max)

 

파일명을 FileName필드에 입력

Byte[]로 변환된 값을 AttachedFile에 입력

 

저장된 DB를 Select해서 첨부파일 저장 이벤트로 Byte[] → File로 변환하면 끗!

 

반응형

'Programming > C#' 카테고리의 다른 글

C# DB연결하기  (0) 2010.02.23
C# Assembly.LoadFrom() DLL불러오기  (0) 2010.02.23
C# PDF파일 다루기  (1) 2010.02.23
C# WebClient를 이용한 자동업데이트  (1) 2010.02.23
C# DevExpress 스킨변경  (0) 2010.02.23