image

 

 

 

            //린큐개체
            Contract.Data.PersonnelPerformanceReviewDetail ppd = this.datagrdPersonnelPerformanceReviewDetail.SelectedItem
                                                                                    as Contract.Data.PersonnelPerformanceReviewDetail; 

            if (ppd != null)
            {
                Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog(); //SaveFileDialog  오픈 
                dlg.DefaultExt = ppd.RatingFileType;
                dlg.Filter =string.Format( "저장된 파일속성 ({0})|{0}" ,ppd.RatingFileType ); //데이터베이스에 저장되어져 있던 ".jpg"
                if (dlg.ShowDialog() == true)
                {
                    string filename = dlg.FileName; //SaveFileDialog 에서 선택된 경로
                    System.Data.Linq.Binary binaryFile = ppd.RatingFile; //바이너리 파일
                    using (System.IO.MemoryStream ms = new System.IO.MemoryStream(binaryFile.ToArray())) 
                    {
                        FileStream outStream = File.OpenWrite(filename);
                        ms.WriteTo(outStream);
                        outStream.Flush();
                        outStream.Close();
                    }

                } 

openFileDialog.ShowDialog를 이용한 파일 기 및 쓰기 테스트 입니다.

데이터베이스에 파일 저장하기

바이너리로 만들어서 데이터베이스에 저장합니다.

데이터베이스 필드형식은 varbinary 설정합니다.

			//저장될 스트림입니다.
            MemoryStream TempMemoryStream = null;
               
            if (this.openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK) //Test_Doc.docx 파일 선택
            {
                Int32 reads = 0;

                FormFileName = System.IO.Path.GetFileName(openFileDialog1.FileName);
                using (Stream st = openFileDialog1.OpenFile())
                using (MemoryStream output = new MemoryStream())
                {
                    st.Position = 0;
                    Byte[] buffer = new Byte[256];

                    while (0 < (reads = st.Read(buffer, 0, buffer.Length)))
                    {
                        output.Write(buffer, 0, reads);
                    }
                    TempMemoryStream = output;
                    output.Flush();

                } //using end 

 

데이터베이스에서 불러오기

				//System.Data.Linq.Binary 형식의 데이터
                System.Data.Linq.Binary binaryFile = item.FormFile; 
                byte[] fileResult = binaryFile.ToArray();
                using (FileStream stream = new FileStream(@"D:\Test_Doc.docx", FileMode.Create))
                {
                    Byte[] bytes = fileResult.ToArray();

                    stream.Write(bytes, 0, bytes.Length);

 

파일저장하기

                    //파일저장하기
                    using (FileStream stream = new FileStream(@"D:\Test_Doc.docx", FileMode.Create))
                    {
                        Byte[] bytes = output.ToArray();

                        stream.Write(bytes, 0, bytes.Length);
                    }

 

 System.Data.Linq.Binary 형식으로 저장
                Int32 reads = 0;

                //임시 메모리스트림에 작성
                using (Stream st = dlg.OpenFile())
                {
                    using (MemoryStream output = new MemoryStream())
                    {
                        st.Position = 0;
                        Byte[] buffer = new Byte[256];

                        while (0 < (reads = st.Read(buffer, 0, buffer.Length)))
                        {
                            output.Write(buffer, 0, reads);
                        }
                        TempMemoryStream = output;
                        output.Flush();
                    } // in using
                } // out using
Personnel.Photo = new System.Data.Linq.Binary(TempMemoryStream.GetBuffer());

Linq.Binary 데이터 바인딩
        public void UpdatePersonImage()
        {
            Contract.Data.Insa.ParentPerson pp = this.MainContentGrid.DataContext as Contract.Data.Insa.ParentPerson;
            if (pp.Personnel.Photo.Length > 0)
            {
                System.Data.Linq.Binary binaryFile = pp.Personnel.Photo;     //Binary  로 저장된 필드       
       
                using( System.IO.MemoryStream ms = new System.IO.MemoryStream( binaryFile.ToArray()))
                {

                    System.Drawing.Bitmap bm = new System.Drawing.Bitmap(ms);
                    this.imgPerson.Source = GetBitmapSource(bm);
                }

            }
        }

        private System.Windows.Media.Imaging.BitmapSource GetBitmapSource(System.Drawing.Bitmap _image)
        {
            System.Drawing.Bitmap bitmap = _image;
            System.Windows.Media.Imaging.BitmapSource bitmapSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
                bitmap.GetHbitmap(),
                IntPtr.Zero,
                Int32Rect.Empty,
                System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
            return bitmapSource;
        }

 

유용한 파일함수

파일이름을 가지고 오고 싶을떄?

Path.GetExtension 메서드
지정된 경로 문자열에서 확장명을 반환합니다.

FormFileName = System.IO.Path.GetFileName(openFileDialog1.FileName);

구조체와 클래스를 파일로 입력 및 출력을 한번에 하기위해서는 Serialize 와 Deserialize를 사용 하여야 합니다.

NET Framework 클래스 라이브러리

BinaryFormatter 생성자 자세히 알아보기

http://msdn.microsoft.com/library/KOR/cpref/html/frlrfSystemRuntimeSerializationFormattersBinaryBinaryFormatterClassctorTopic.asp?frame=true

using System.Runtime.Serialization.Formatters.Binary;
using System.IO;

클래스 저장하기

   //Class Save

저장하고자 하는 클래스
   Class1 c1 = new Class1("kojaedoo");

/*

using System;

namespace Test
{

[Serializable()] <----꼭 해주어야 합니당
public class Class1
{

  string name;
  public Class1(string name)
  {
   //
   // TODO: 여기에 생성자 논리를 추가합니다.
   //
   this.name = name;
  }
}

}

*/
   BinaryFormatter serializer = new BinaryFormatter(); 

저장하고자 하는 파일네임

   Stream stream = File.Open("data.txt", FileMode.Create);

   serializer.Serialize(stream ,c1);
   stream.Close();

   c1 = null;

클래스 불러오기

   //Class Open
   stream = File.Open( "data.txt", FileMode.Open  );

   BinaryFormatter formatter = new BinaryFormatter();

   Class1 c3 = (Class1)formatter.Deserialize( stream );

   MessageBox.Show( "data.txt에서 가지고 온값::::"+c3.Name );

ex)

        [Serializable]

        public class st_Option

        {

            public int[]        nData=new int [10];

            public double[] dblData=new double [10];

            public string[] szData=new string [10];

        }

선언은 위와 같이 해주시면 되고,

using System.Runtime.Serialization.Formatters.Binary;

            // Serialize하는 경우

            st_Option op=new st_Option ();

            DateTime time=DateTime.Now;

            op.szData[0]=time.Ticks.ToString();

            FileStream fs = new FileStream("DataFile.dat", FileMode.Create);

            BinaryFormatter bf = new BinaryFormatter();

            bf.Serialize(fs, op); 

            fs.Close();

            // Deserialize 하는 경우

            FileStream fs = new FileStream("DataFile.dat", FileMode.Open);

            BinaryFormatter bf = new BinaryFormatter();

            Define.st_Option op=null;

            op=(Define.st_Option)bf.Deserialize(fs);

            fs.Close();

            //op.nData[0] 에 들어간 값 확인

            MessageBox.Show(op.nData[0].ToString());

출처 : http://www.devpia.com/Forum/BoardView.aspx?no=52583&ref=52583&page=1&forumname=CSHARP_QA&stype=&KeyW=%b1%b8%c1%b6%c3%bc&KeyR=title

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
public partial class Test_CreateForder : System.Web.UI.Page
{

    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {

        string ForderURL = @"D:\WEBSITE\PHOTO_DATA\";
        string ForderURLToTal = @"D:\WEBSITE\PHOTO_DATA\" + this.TextBox1.Text;
        string ForderName = this.TextBox1.Text;
        string ReadForder = string.Empty;;
        //Response.Write("들어가기전"+ForderName+"<br>-------------------------------<Br>");
        try
        {
            int AddForderNumber = 1;
            //중복디렉토리 있다 ㅜ_ㅜ
            if (!Directory.Exists(ForderURL + ForderName))
            {
                ReadForder = ForderName;
                //Response.Write("원래이름 통과!<br>");

            }
            else
            {

                while (Directory.Exists(ForderURL + ForderName))
                {

                    string Temp = ForderName + "(" + AddForderNumber.ToString() + ")";
                    AddForderNumber++;
                    if (!Directory.Exists(ForderURL + Temp))
                    {
                        //만약 새로만든 디렉토리 이름으로  디렉토리가 없다면~!
                        ReadForder = Temp;
                        break;
                    }
                                 }
            }

            System.IO.Directory.CreateDirectory(ForderURL + ReadForder );
                  }
        catch (Exception ex) {

                     Response.Write(ex.ToString());
        }

    }
}

DriveInfo 클래스

참고: 이 클래스는 .NET Framework 버전 2.0에서 새로 추가되었습니다.

드라이브 정보에 액세스합니다.

네임스페이스: System.IO
어셈블리: mscorlib(mscorlib.dll)

protected void Page_Load(object sender, EventArgs e)
    {

        DriveInfo[] allDrives = DriveInfo.GetDrives();

        foreach (DriveInfo d in allDrives)
        {
            Response.Write(string.Format("Drive {0}<br>", d.Name));
            Response.Write(string.Format("  File type: {0}<br>", d.DriveType));
            if (d.IsReady == true)
            {

                Response.Write(string.Format("  Volume label: {0}<br>", d.VolumeLabel));
                Response.Write(string.Format("  File system: {0}<br>", d.DriveFormat));
                Response.Write( string.Format("  Available space to current user:{0, 15} bytes<br>", d.AvailableFreeSpace) );

                Response.Write(string.Format("  Total available space:          {0, 15} bytes<br>", d.TotalFreeSpace));

                Response.Write(string.Format("  Total size of drive:            {0, 15} bytes<br> ", d.TotalSize));
            }
        }

    }

/*
This code produces output similar to the following:
Drive A:\
  File type: Removable
Drive C:\
  File type: Fixed
  Volume label:
  File system: FAT32
  Available space to current user:     4770430976 bytes
  Total available space:               4770430976 bytes
  Total size of drive:                10731683840 bytes
Drive D:\
  File type: Fixed
  Volume label:
  File system: NTFS
  Available space to current user:    15114977280 bytes
  Total available space:              15114977280 bytes
  Total size of drive:                25958948864 bytes
Drive E:\
  File type: CDRom
The actual output of this code will vary based on machine and the permissions
granted to the user executing it.
*/

ms-help://MS.VSCC.v80/MS.MSDN.v80/MS.NETDEVFX.v20.ko/cpref8/html/T_System_IO_DriveInfo.htm

DriveInfo 멤버

Public 생성자

이름
설명


:Track('ctl00_LibFrame_ctl02|ctl00_LibFrame_ctl03',this);" href="http://msdn2.microsoft.com/ko-kr/library/system.io.driveinfo.driveinfo(VS.80).aspx">DriveInfo


지정된 드라이브의 정보에 액세스합니다.

위쪽

Public 속성

이름
설명


:Track('ctl00_LibFrame_ctl04|ctl00_LibFrame_ctl05',this);" href="http://msdn2.microsoft.com/ko-kr/library/system.io.driveinfo.availablefreespace(VS.80).aspx">AvailableFreeSpace


드라이브의 사용 가능한 공간을 나타냅니다.


:Track('ctl00_LibFrame_ctl04|ctl00_LibFrame_ctl06',this);" href="http://msdn2.microsoft.com/ko-kr/library/system.io.driveinfo.driveformat(VS.80).aspx">DriveFormat
NTFS 또는 FAT32와 같은 파일 시스템의 이름을 가져옵니다.


:Track('ctl00_LibFrame_ctl04|ctl00_LibFrame_ctl07',this);" href="http://msdn2.microsoft.com/ko-kr/library/system.io.driveinfo.drivetype(VS.80).aspx">DriveType
드라이브 형식을 가져옵니다.


:Track('ctl00_LibFrame_ctl04|ctl00_LibFrame_ctl08',this);" href="http://msdn2.microsoft.com/ko-kr/library/system.io.driveinfo.isready(VS.80).aspx">IsReady
드라이브가 준비되었는지 여부를 나타내는 값을 가져옵니다.


:Track('ctl00_LibFrame_ctl04|ctl00_LibFrame_ctl09',this);" href="http://msdn2.microsoft.com/ko-kr/library/system.io.driveinfo.name(VS.80).aspx">Name
드라이브 이름을 가져옵니다.


:Track('ctl00_LibFrame_ctl04|ctl00_LibFrame_ctl10',this);" href="http://msdn2.microsoft.com/ko-kr/library/system.io.driveinfo.rootdirectory(VS.80).aspx">RootDirectory
드라이브의 루트 디렉터리를 가져옵니다.


:Track('ctl00_LibFrame_ctl04|ctl00_LibFrame_ctl11',this);" href="http://msdn2.microsoft.com/ko-kr/library/system.io.driveinfo.totalfreespace(VS.80).aspx">TotalFreeSpace
드라이브의 사용 가능한 공간 합계를 가져옵니다.


:Track('ctl00_LibFrame_ctl04|ctl00_LibFrame_ctl12',this);" href="http://msdn2.microsoft.com/ko-kr/library/system.io.driveinfo.totalsize(VS.80).aspx">TotalSize
드라이브에 있는 저장소 공간의 크기 합계를 가져옵니다.


:Track('ctl00_LibFrame_ctl04|ctl00_LibFrame_ctl13',this);" href="http://msdn2.microsoft.com/ko-kr/library/system.io.driveinfo.volumelabel(VS.80).aspx">VolumeLabel
드라이브의 볼륨 레이블을 가져오거나 설정합니다.

http://msdn2.microsoft.com/ko-kr/library/system.io.driveinfo_members(VS.80).aspx

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace ezhanja.Testing.FileUpload
{
/// <summary>
/// WebForm1에 대한 요약 설명입니다.
/// </summary>
public class WebForm1 : System.Web.UI.Page
{
  protected System.Web.UI.HtmlControls.HtmlInputFile File1;
  protected System.Web.UI.WebControls.Label Label1;
  protected System.Web.UI.WebControls.Label Label2;
  protected System.Web.UI.HtmlControls.HtmlInputButton Submit1;
  private void Page_Load(object sender, System.EventArgs e)
  {
   // 여기에 사용자 코드를 배치하여 페이지를 초기화합니다.
   Response.Write( Server.MapPath("\\저장위치") );
  }

  #region Web Form 디자이너에서 생성한 코드
  override protected void OnInit(EventArgs e)
  {
   //
   // CODEGEN: 이 호출은 ASP.NET Web Form 디자이너에 필요합니다.
   //
   InitializeComponent();
   base.OnInit(e);
  }
  /// <summary>
  /// 디자이너 지원에 필요한 메서드입니다.
  /// 이 메서드의 내용을 코드 편집기로 수정하지 마십시오.
  /// </summary>
  private void InitializeComponent()
  {   
   this.Submit1.ServerClick += new System.EventHandler(this.Submit1_ServerClick);
   this.Load += new System.EventHandler(this.Page_Load);

  }
  #endregion

  private void Submit1_ServerClick(object sender, System.EventArgs e)
  {
   if ( (this.File1.PostedFile !=null) && (this.File1.PostedFile.ContentLength > 0 ) )
   {    
    try
    {
string lastSaveName =  SaveFile(this.File1); 호출
     Response.Write("마지막저장:"+lastSaveName);
    }
    catch(System.Exception es){
     this.Label2.Text ="<br><b>"+es.ToString()+"</b>";    
    }   

   }
   else
   {
    this.Label1.Text ="업로드파일을 선택해주세요!";
   }
  }

  public string SaveFile(System.Web.UI.HtmlControls.HtmlInputFile hFile){
//Util.Util.saveDataPath는 파일이 저장되는 위치입니당.~
   //세이브
   string LastSaveName;
   //경로를 포함한 전체이름
    string totalFileName =  hFile.PostedFile.FileName;    
   //파일네임
    string realFileName = System.IO.Path.GetFileName(totalFileName);

   if(!CheckSameFile(realFileName))
   {
    //Response.Write("중복되는 이름없따 저장완료!!!");
    hFile.PostedFile.SaveAs( Util.Util.saveDataPath+realFileName );
    LastSaveName=realFileName;
   }
   else{    
    //파일확장명
    string fileExtension = System.IO.Path.GetExtension( realFileName );
    //확장명을 땐파일 네임 
    string fileNameWithoutExtension= System.IO.Path.GetFileNameWithoutExtension(realFileName);
    string TempRealFileName = realFileName; //확장자까지 붙어있는 파일네임 test.aspx
    //같은 파일네임이있다면 계속돌아주라
    int i=1;
    while( CheckSameFile(TempRealFileName) )
    {
     string TempFileNameWithoutExtension = System.IO.Path.GetFileNameWithoutExtension(realFileName);
     string TempFileExtension = System.IO.Path.GetExtension( TempRealFileName );
     TempRealFileName=TempFileNameWithoutExtension+"("+i+")"+TempFileExtension;
     i++;
    }

    //실질적인 저장
    hFile.PostedFile.SaveAs( Util.Util.saveDataPath+ TempRealFileName );
    LastSaveName = TempRealFileName;
   }  
   return LastSaveName;  
  }

  #region 같은 파일네임 체크
  /// <summary>
  /// 디렉토리에 같은 파일이 있는지를 체크합니다.
  /// 파일은 Util.Util.saveDataPath 에서 체크합니다.
  /// </summary>
  /// <returns>파일이있으면 true 없으면 false </returns>
  public bool CheckSameFile( string fileName)
  {

   if ( System.IO.File.Exists(Util.Util.saveDataPath+fileName) )
   {
    return true;
   }
   else{
    return false;
   }
  }

  /// <summary>
  /// 경로와 파일네임을 입력하면 파일이 있는지 없는지를 체크합니다
  /// </summary>
  /// <param name="filePath">파일디렉토리</param>
  /// <param name="fileName">검색하고자 하는 파일네임</param>
  /// <returns>파일이있으면 true 없으면 false </returns>
  public bool CheckSameFile(string filePath , string fileName){
   if ( System.IO.File.Exists(filePath+fileName) )
   {
    return true;
   }
   else
   {
    return false;
   }
  }

  #endregion
}

}

간단한 방법

//Class Save
   Class1 c1 = new Class1("kojaedoo");
   BinaryFormatter serializer = new BinaryFormatter();  
   Stream stream = File.Open("data.txt", FileMode.Create);
   serializer.Serialize(stream ,c1);   
   stream.Close();
   c1 = null;

   //Class Open
   stream = File.Open( "data.txt", FileMode.Open  );
   BinaryFormatter formatter = new BinaryFormatter();

   Class1 c3 = (Class1)formatter.Deserialize( stream );
   MessageBox.Show( "클래스에서 가지고 온값::::"+c3.GetName());

 

 

MSDN Home >  Visual Studio .NET >  Visual Basic 및 Visual C# >  구성 요소를 사용한 프로그래밍 >  구성 요소 제작 >  구성 요소에서 속성, 메서드, 멤버 및 이벤트의 구현 
Visual Basic 및 Visual C# 개념  

구성 요소의 속성 저장


가끔 구성 요소의 상태를 저장해야 하는 경우가 있습니다. 이러한 경우에는 예를 들어, 구성 요소의 사용자에 대한 개별 정보를 저장하거나 사용자 지정 컨트롤의 기본 구성을 변경합니다.

serialization이라는 과정을 통해 구성 요소의 상태를 파일에 저장할 수 있습니다. serialize하면 개체를 데이터 스트림으로 변환한 다음 파일에 저장할 수 있습니다. 또한 스트림은 다시 deserialization을 통해 개체로 변환될 수 있습니다.

.NET Framework는 serialization을 위해 다음과 같은 두 가지 포맷터, 즉 BinaryFormatter 클래스 및 SOAPFormatter 클래스를 제공합니다. 이 클래스는 현재 메모리에 있는 개체의 내부 메모리를 표현한 개체 그래프를 사용하여 데이터 스트림으로 변환합니다. 각 포맷터의 기능은 이름에 잘 나타나 있습니다. BinaryFormatter는 개체 그래프를 데스크톱 응용 프로그램에서 가장 유용하게 사용되는 이진 스트림으로 변환하고 SOAPFormatter는 개체 그래프를 인터넷 응용 프로그램에서 가장 유용하게 사용되는 SOAP(Simple Object Access Protocol) 형식으로 변환합니다. 그러면 이 스트림은 deserialize될 수 있는 파일로 저장될 수 있고 필요하면 다시 개체로 변환될 수 있습니다.

스트림 Serialization
구성 요소의 상태를 저장하려면

SerializableAttribute 특성을 serialize할 구성 요소에 적용합니다.
' Visual Basic
<Serializable()> Public Class Account
   ' Insert code to implement class.
End Class

// C#
[Serializable()]
public class Account
{
   // ' Insert code to implement class.
}
이 클래스의 인스턴스를 저장할 개체로 만듭니다.
' Visual Basic
Dim myAccount As New Account()

// C#
Account myAccount = new Account();
Stream 개체를 serialize된 데이터에 리포지토리를 제공하는 파일로 만듭니다.
' Visual Basic
Imports System.IO
' This creates a new file with the name SavedAccount.txt, and creates
' a Stream object to write data to that file. The GetFolderPath method
' is used to get the path to the current user's Personal folder.
Dim myFileStream As Stream = File.Create _
   (System.Environment.GetFolderPath _
      (System.Environment.SpecialFolder.Personal))

// C#
using System.IO;
// This creates a new file with the name SavedAccount.txt, and creates
// a Stream object to write data to that file. The GetFolderPath method
// is used to get the path to the current user's Personal folder.
Stream myFileStream = File.Create
   (System.Environment.GetFolderPath
      (System.Environment.SpecialFolder.Personal));
포맷터 클래스의 인스턴스를 만듭니다.
개체 그래프를 이진 스트림으로 변환하려면 BinaryFormatter 클래스의 인스턴스를 만듭니다.
' Visual Basic
Imports System.Runtime.Serialization.Formatters.Binary
Dim serializer As New BinaryFormatter()

// C#
using System.Runtime.Serialization.Formatters.Binary;
BinaryFormatter serializer = new BinaryFormatter();
개체 그래프를 SOAP 스트림으로 변환하려면 SoapFormatter 클래스의 인스턴스를 만듭니다.
참고   프로젝트에 System.Runtime.Serialization.Formatters.Soap 네임스페이스에 대한 참조가 있어야 합니다.
' Visual Basic
Imports System.Runtime.Serialization.Formatters.Soap
Dim serializer as New SoapFormatter

// C#
using System.Runtime.Serialization.Formatters.Soap;
SoapFormatter serializer = new SoapFormatter();
포맷터의 Serialize 메서드를 호출하여 개체를 Stream에 씁니다.
' Visual Basic
serializer.Serialize(myFileStream, myAccount)
myFileStream.Close()

// C#
serializer.Serialize(myFileStream, myAccount);
myFileStream.Close();
파일 스트림을 닫고 serialization을 완료합니다.
이제 SavedAccount.txt 파일에 개체의 인스턴스가 이진 형식으로 저장되었습니다.

스트림 Deserialization
개체를 저장한 다음 나중에 검색할 수 있습니다. 구성 요소를 serialize할 때 사용한 것과 동일한 포맷터를 deserialization에 사용할 수 있습니다.

저장된 구성 요소를 복원하려면

복원할 클래스와 동일한 형식의 변수를 선언합니다.
' Visual Basic
Dim restoredAccount As Account

// C#
Account restoredAccount;
Stream 개체를 만들고 serialize된 개체가 있는 파일을 엽니다.
' Visual Basic
Imports System.IO
Dim myFileStream As Stream = File.OpenRead _
   (System.Environment.GetFolderPath _
      (System.Environment.SpecialFolder.Personal))

// C#
using System.IO;
Stream myFileStream = File.OpenRead
   (System.Environment.GetFolderPath
      (System.Environment.SpecialFolder.Personal));
데이터를 serialize하는 데 사용한 것과 동일한 형식으로 포맷터 클래스의 인스턴스를 만듭니다.
다음 예제에서는 BinaryFormatter 클래스를 사용하는 방법을 보여 줍니다.
' Visual Basic
Imports System.Runtime.Serialization.Formatters.Binary
Dim deserializer As New BinaryFormatter()

// C#
using System.Runtime.Serialization.Formatters.Binary;
BinaryFormatter deserializer = new BinaryFormatter();
다음 예제에서는 SoapFormatter 클래스를 사용하는 방법을 보여 줍니다.
참고   프로젝트에 System.Runtime.Serialization.Formatters.Soap 네임스페이스에 대한 참조가 있어야 합니다.
' Visual Basic
Imports System.Runtime.Serialization.Formatters.Soap
Dim deserializer As New SoapFormatter()

// C#
using System.Runtime.Serialization.Formatters.Soap;
SoapFormatter deserializer = new SoapFormatter();
파일 스트림을 개체 그래프로 변환하려면 포맷터의 Deserialize 메서드를 호출하고 개체 그래프를 원하는 형식의 개체로 변환하려면 CType 함수(Visual Basic) 또는 명시적 캐스트(C#)를 사용합니다.
' Visual Basic
' The CType function converts the file stream specified in the first
' argument to an object of the type specified in the second argument.
' If the object in the first argument cannot be converted to the
' specified type, an error will result.
restoredAccount = CType(deserializer.Deserialize(myFileStream), _
   Account)
myFileStream.Close()

// C#
// The explicit cast converts the file stream to an object of the type // specified. If the object in the file stream cannot be converted to // the specified type, an error will result.
restoredAccount = (Account)(deserializer.Deserialize(myFileStream));
myFileStream.Close();
보안 정보   이 기술은 데이터 보안에 적합하지 않으므로 중요하거나 기밀을 요하는 데이터를 저장하는 데는 이 기술을 사용하지 마십시오. 데이터의 보안 암호화 스키마를 만드는 방법에 대한 자세한 내용은 System.Security.Cryptography 네임스페이스를 참조하십시오.
참고 항목
BinaryFormatter 클래스 | SOAPFormatter 클래스 | SerializableAttribute 클래스 | System.Security.Cryptography 네임스페이스 | 구성 요소 제작

http://msdn.microsoft.com/library/KOR/vbcon/html/vbtsksavingpropertiesofyourcontrol.asp?frame=true

DriveInfo 클래스

참고: 이 클래스는 .NET Framework 버전 2.0에서 새로 추가되었습니다.

드라이브 정보에 액세스합니다.

네임스페이스: System.IO
어셈블리: mscorlib(mscorlib.dll)

protected void Page_Load(object sender, EventArgs e)
    {

        DriveInfo[] allDrives = DriveInfo.GetDrives();

        foreach (DriveInfo d in allDrives)
        {
            Response.Write(string.Format("Drive {0}<br>", d.Name));
            Response.Write(string.Format("  File type: {0}<br>", d.DriveType));
            if (d.IsReady == true)
            {

                Response.Write(string.Format("  Volume label: {0}<br>", d.VolumeLabel));
                Response.Write(string.Format("  File system: {0}<br>", d.DriveFormat));
                Response.Write( string.Format("  Available space to current user:{0, 15} bytes<br>", d.AvailableFreeSpace) );

                Response.Write(string.Format("  Total available space:          {0, 15} bytes<br>", d.TotalFreeSpace));

                Response.Write(string.Format("  Total size of drive:            {0, 15} bytes<br> ", d.TotalSize));
            }
        }

    }

/*
This code produces output similar to the following:
Drive A:\
  File type: Removable
Drive C:\
  File type: Fixed
  Volume label:
  File system: FAT32
  Available space to current user:     4770430976 bytes
  Total available space:               4770430976 bytes
  Total size of drive:                10731683840 bytes
Drive D:\
  File type: Fixed
  Volume label:
  File system: NTFS
  Available space to current user:    15114977280 bytes
  Total available space:              15114977280 bytes
  Total size of drive:                25958948864 bytes
Drive E:\
  File type: CDRom
The actual output of this code will vary based on machine and the permissions
granted to the user executing it.
*/

ms-help://MS.VSCC.v80/MS.MSDN.v80/MS.NETDEVFX.v20.ko/cpref8/html/T_System_IO_DriveInfo.htm

DriveInfo 멤버

Public 생성자

이름
설명


DriveInfo
지정된 드라이브의 정보에 액세스합니다.

위쪽

Public 속성

이름
설명


AvailableFreeSpace
드라이브의 사용 가능한 공간을 나타냅니다.


DriveFormat
NTFS 또는 FAT32와 같은 파일 시스템의 이름을 가져옵니다.


DriveType
드라이브 형식을 가져옵니다.


IsReady
드라이브가 준비되었는지 여부를 나타내는 값을 가져옵니다.


Name
드라이브 이름을 가져옵니다.


RootDirectory
드라이브의 루트 디렉터리를 가져옵니다.


TotalFreeSpace
드라이브의 사용 가능한 공간 합계를 가져옵니다.


TotalSize
드라이브에 있는 저장소 공간의 크기 합계를 가져옵니다.


VolumeLabel
드라이브의 볼륨 레이블을 가져오거나 설정합니다.

http://msdn2.microsoft.com/ko-kr/library/system.io.driveinfo_members(VS.80).aspx

Directory.GetCurrentDirectory();

 

.NET Framework 클래스 라이브러리

Directory.GetCurrentDirectory 메서드

응용 프로그램의 현재 작업 디렉터리를 가져옵니다.

네임스페이스: System.IO
어셈블리: mscorlib(mscorlib.dll)

 

출처 : http://msdn.microsoft.com/ko-kr/library/system.io.directory.getcurrentdirectory(VS.80).aspx

+ Recent posts