반응형

* C# XML File Write & Read 예제...

 

메인 화면

전체 소스 코드

Form1.cs

 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace CSharp_XMLFile
{
    public partial class Form1 : Form
    {
        string strLocalFolder = Application.ExecutablePath.Substring(0, Application.ExecutablePath.LastIndexOf('\\'));
        string strXmlFile = "\\XMLText.xml";

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //파일이 존재 하면 삭제 하고 다시...
            if(System.IO.File.Exists(strLocalFolder + strXmlFile ))
            {
                System.IO.File.Delete(strLocalFolder + strXmlFile );
            }

            //XML Create
            System.Xml.XmlDocument xdDoc = new System.Xml.XmlDocument();
            System.Xml.XmlNode xnRoot = xdDoc.CreateElement("테스트");

            System.Xml.XmlNode xnTmp = xdDoc.CreateElement("XMLFileEx");
            xnTmp.InnerText = "XML Test";

            //상위 노드에 xnTmp 노드를 추가 테스트 -> XMLFileEx 관계
            xnRoot.AppendChild(xnTmp);

            //CheckBox 저장
            System.Xml.XmlNode xnCheckBox = xdDoc.CreateElement("ProgramCheckBox");
            System.Xml.XmlAttribute xaCheck1 = xdDoc.CreateAttribute("CheckBox1");
            System.Xml.XmlAttribute xaCheck2 = xdDoc.CreateAttribute("CheckBox2");
            System.Xml.XmlAttribute xaCheck3 = xdDoc.CreateAttribute("CheckBox3");

            xaCheck1.Value = checkBox1.Checked.ToString();
            xaCheck2.Value = checkBox2.Checked.ToString();
            xaCheck3.Value = checkBox3.Checked.ToString();

            //xnCheckBox 노드에 속성 추가
            xnCheckBox.Attributes.Append(xaCheck1);
            xnCheckBox.Attributes.Append(xaCheck2);
            xnCheckBox.Attributes.Append(xaCheck3);


            //라디오 버튼 저장
            System.Xml.XmlNode xnRadio = xdDoc.CreateElement("ProgramRadio");
            System.Xml.XmlAttribute xaRadio1 = xdDoc.CreateAttribute("Radio1");
            System.Xml.XmlAttribute xaRadio2 = xdDoc.CreateAttribute("Radio2");
            System.Xml.XmlAttribute xaRadio3 = xdDoc.CreateAttribute("Radio3");

            xaRadio1.Value = radioButton1.Checked.ToString();
            xaRadio2.Value = radioButton2.Checked.ToString();
            xaRadio3.Value = radioButton3.Checked.ToString();

            //XnRadio 노드에 속성 추가
            xnRadio.Attributes.Append(xaRadio1);
            xnRadio.Attributes.Append(xaRadio2);
            xnRadio.Attributes.Append(xaRadio3);
            

            xnRoot.AppendChild(xnRadio);
            xnRoot.AppendChild(xnCheckBox);

            //XML 저장
            xdDoc.AppendChild(xnRoot);
            xdDoc.Save(strLocalFolder + strXmlFile);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            //XML Read

            //파일이 존재 하지 않으면...
            if (!System.IO.File.Exists(strLocalFolder + strXmlFile)) return;

            textBox1.Text = "";

            System.Xml.XmlDocument xdDoc = new System.Xml.XmlDocument();
            //XML 파일 로드...
            xdDoc.Load(strLocalFolder + strXmlFile);

            //테스트 노드 의 하위 노드들 읽기...
            foreach (System.Xml.XmlNode xn in xdDoc.ChildNodes )
            {
                textBox1.Text +="RootNode = " + xn.Name + System.Environment.NewLine ;
                textBox1.Text += "하위 노드"+ System.Environment.NewLine;
                //하위 노드... Root 노드에 대한
                foreach (System.Xml.XmlNode xx in xn)
                {
                    //XMLFileEx
                    //ProgramCheckBox
                    //ProgramRadio
                    if(xx.Name == "XMLFileEx")
                    {
                        textBox1.Text += "RootNode ->" + xx.Name + System.Environment.NewLine;
                        textBox1.Text += "           " + xx.InnerText  + System.Environment.NewLine;
                    }
                    else if (xx.Name == "ProgramCheckBox")
                    {
                        textBox1.Text += "RootNode ->" + xx.Name + System.Environment.NewLine;
                        textBox1.Text += "           CheckBox1 = " + xx.Attributes[0].Value.ToString() + System.Environment.NewLine;
                        textBox1.Text += "           CheckBox2 = " + xx.Attributes[1].Value.ToString() + System.Environment.NewLine;
                        textBox1.Text += "           CheckBox3 = " + xx.Attributes[2].Value.ToString() + System.Environment.NewLine;
                    }
                    else
                    {
                        textBox1.Text += "RootNode ->" + xx.Name + System.Environment.NewLine;
                        textBox1.Text += "           Radio1 = " + xx.Attributes[0].Value.ToString() + System.Environment.NewLine;
                        textBox1.Text += "           Radio2 = " + xx.Attributes[1].Value.ToString() + System.Environment.NewLine;
                        textBox1.Text += "           Radio3 = " + xx.Attributes[2].Value.ToString() + System.Environment.NewLine;
                    }

                }
            }

        }
    }
}

 

 

 

* 예제 결과

 

- 파일 저장 위치 및 파일 내용

파일 저장 위치

 

아래의 그림은 XML 파일 만들기 버튼 클릭 이후 메모장으로 XML 파일 열어본 결과

파일 내용
결과 화면

 

 

반응형
반응형

* AndroidMenifest.xml  - 액션바 색상 변경,  앱 아이콘 변경, 이름 변경

 

<application
    android:allowBackup="true"
    android:icon="@mipmap/mainicon1"     <- 아이콘 변경 부분
    android:label="@string/app_name"     <- 앱 이름 변경 부분 string/app_name 은 선언 부분으로 찾아 가야됨 string.xml로
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".MediumActivity"></activity>
</application

* color.xml style.xml 액션바 색상 변경

 

<resources>            *style.xml 부분

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/dimgray</item>         <- color.xml 에 color 추가된 부분을 여기에 적용
        <item name="colorPrimaryDark">@color/Black</item>       <- color.xml 에 color 추가된 부분을 여기에 적용
        <item name="colorAccent">@color/colorAccent</item>
    </style>
 

 

<?xml version="1.0" encoding="utf-8"?>
<resources>           *color.xml 부분
    <color name="colorPrimary">#3F51B5</color>
    <color name="colorPrimaryDark">#303F9F</color>
    <color name="colorAccent">#FF4081</color>
    <color name="Black">#000</color>                <- color 추가된 부분
    <color name="dimgray">#696969</color>           <- color 추가된 부분
</resources>  

 

* strings.xml 어플 이름 변경

 

<resources>
    <string name="app_name">ButtonEx</string>
</resources>

 

https://kdsoft-zeros.tistory.com/43

 

[Android] 어플 아이콘 변경

* 어플 아이콘 변경 방법 안드로이드를 설치 하고 프로젝트를 작성 했다면 C:\Users\Administrator\AndroidStudioProjects\VisualProgramming\app\src\main\res 위의 경로에 보통 만들어 짐. 위 폴더에 들어 가게..

kdsoft-zeros.tistory.com

 

반응형
반응형

* VBNET 동적으로 DLL 로드 하여 그 안에 포함된 Form 과 클래스 함수 사용 예제...

테스트 DLL 위치는 위와 같이 그냥 C:\\ 에 놔두었는데 위치는 사용자 맘대로 두어도 괜찮겠습니다.

나중에 소스코드에서 DLL 로드 위치를 사용자가 Dll 이 있는 위치로 지정 하면 되겠습니다.

 

위의 테스트 DLL 은 C# 으로 만들어진 클래스 라이브러리 이며, VBNET 과 C# 은 닷넷 프레임 워크 기반

으로 하는 언어로 둘이 호환성은 아주 좋습니다. VBNET 으로 만들어진 DLL 이나 C# 으로 만들어진 DLL

이나 상관이 없으므로 기존 C# 으로 만들어진 테스트 DLL 을 사용 하였습니다.

 

메인 화면

전체 소스 코드

Form1.vb

 

Public Class Form1

    Dim ab As System.Reflection.Assembly

    Private Sub button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles button1.Click
        Dim ofd As OpenFileDialog = New OpenFileDialog()
        'DLL 파일만 열 수 있게끔...
        ofd.Filter = "Dll File (*.dll) | *.dll"

        If ofd.ShowDialog() = Windows.Forms.DialogResult.OK Then

            '선택된 dll 파일 표시...
            label1.Text = ofd.FileName

            '동적 dll 로드
            ab = System.Reflection.Assembly.LoadFile("C:\ClassLibrary1.dll")

        End If

    End Sub

    Private Sub button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles button2.Click
        '폼 불러오기...

        '파일이 존재 하지 않으면...
        If Not System.IO.File.Exists(label1.Text) Then Return

        'Form
        If (Not ab Is Nothing) Then
            Dim tp() As Type = ab.GetExportedTypes()

            If (tp.Length > 0) Then
                For Each t As Type In tp
                    'Form 이름 찾기
                    If (t.Name = "Form1") Then

                        '객체화
                        Dim ob As Object = Activator.CreateInstance(t)

                        '폼 객체로 변환...
                        Dim f As Form = CType(ob, Form)

                        '폼 실행...
                        f.Show()
                    End If
                Next
            End If

        End If

    End Sub

    Private Sub button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles button3.Click
        '클래스 불러오기...

        '파일이 존재 하지 않으면...
        If Not System.IO.File.Exists(label1.Text) Then Return

        '클래스 찾기
        If (Not ab Is Nothing) Then
            Dim tp() As Type = ab.GetExportedTypes()

            If (tp.Length > 0) Then
                For Each t As Type In tp
                    '클래스 이름 찾기
                    If (t.Name = "Class1") Then
                        '객체화
                        Dim ob As Object = Activator.CreateInstance(t)
                        '클래스 함수 얻어 오기...
                        Dim mt As System.Reflection.MethodInfo = t.GetMethod("Test")

                        'MethodInfo 인보크 전달인자 : 객체화된 클래스, 클래스 함수 전달인자 값
                        '클래스 함수 리턴값 받아오기...

                        '첫번째 방식...
                        '함수 전달 인자 값 셋팅...
                        'Dim obValue(1) As Object
                        'obValue(0) = 200
                        'obValue(1) = 300
                        'Dim vReturn As Object = mt.Invoke(ob, obValue)

                        '두번째 방식...
                        Dim vReturn As Object = mt.Invoke(ob, New Object() {299, 300})


                        MessageBox.Show(vReturn.ToString())
                        
                    End If
                Next
            End If

        End If

    End Sub
End Class

 

* 폼 불러오기

* 클래스 함수 불러오기

* 예제 결과 화면

 

폼 불러오기 결과 화면

 

 

클래스 함수 불러오기 결과 화면


↓아래는C#으로클래스라이브러리(DLL)만드는방법과위와같이동적으로DLL호출하는방법

https://kdsoft-zeros.tistory.com/61

 

[C#] 동적 DLL 폼 (From) 불러오기 또는 클래스 (Class) 함수 불러오기 예제

* 동적으로 DLL 로드 하여 그 안에 포함된 Form 과 클래스 함수 사용 예제... 시작 하기에 앞서 테스트 DLL 만들기... 그대로 ClassLibrary1 을 사용 하여 만들어서 DLL 안에 내용은 아래의 그림과 같이 폼 하나..

kdsoft-zeros.tistory.com

 

반응형
반응형

* 동적으로 DLL 로드 하여 그 안에 포함된 Form 과 클래스 함수 사용 예제...

 

시작 하기에 앞서 테스트 DLL 만들기...

 

그대로 ClassLibrary1 을 사용 하여 만들어서 DLL 안에 내용은 아래의 그림과 같이

폼 하나 클래스 하나를 만들어 보았습니다. 클래스 안에는 테스트 하는 함수 하나를 만들었습니다.

이제 테스트 DLL 도 만들었고 준비도 다 되었으니 동적으로 DLL 을 로드 하여 저 안에 있는 클래스 함수

와 폼을 사용 해 보도록 하겠습니다.

 

테스트 DLL 위치는 위와 같이 그냥 C:\\ 에 놔두었는데 위치는 사용자 맘대로 두어도 괜찮겠습니다.

나중에 소스코드에서 DLL 로드 위치를 사용자가 Dll 이 있는 위치로 지정 하면 되겠습니다.

 

메인화면...

전체 소스 코드

Form1.cs

 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace CSharp_동적Dll
{
    public partial class Form1 : Form
    {
        System.Reflection.Assembly ab;

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();

            //DLL 파일만 열수 있게끔...
            ofd.Filter = "Dll File (*.dll) | *.dll";

            if (ofd.ShowDialog() == DialogResult.OK)
            {
                //선택된 dll 파일 표시...
                label1.Text = ofd.FileName;

                //동적 dll 로드
                ab = System.Reflection.Assembly.LoadFile("C:\\ClassLibrary1.dll");
            }

        }

        private void button2_Click(object sender, EventArgs e)
        {
        	//파일이 존재 하지 않으면...
            if (!System.IO.File.Exists(label1.Text)) return;
            //form
            if (ab != null)
            {
                Type[] tp = ab.GetExportedTypes();

                if (tp.Length > 0)
                {
                    foreach (Type t in tp)
                    {
                        //Form 이름 Form1
                        if (t.Name == "Form1")
                        {
                            //객체화 
                            object ob = Activator.CreateInstance(t);
                            //폼 객체로 변환
                            Form f = ob as Form;
                            f.Show();
                        }
                    }
                }

            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            //파일이 존재 하지 않으면...
            if (!System.IO.File.Exists(label1.Text)) return;
            //class
            if (ab != null)
            {
                Type[] tp = ab.GetExportedTypes();

                if (tp.Length > 0)
                {
                    foreach (Type t in tp)
                    {
                        //class 이름
                        if (t.Name == "Class1")
                        {
                            //클래스 함수 얻어 오기...
                            System.Reflection.MethodInfo mt = t.GetMethod("Test");
                            //객체화 
                            object ob = Activator.CreateInstance(t);

                            //MethodInfo 인보크 (객체화 한 클래스, 함수 전달 인자)
                            //vReturn : 함수 결과값 리턴값...
                            var vReturn = mt.Invoke(ob, new object[] { 299, 300 });
                            
                            //함수 결과값...
                            MessageBox.Show(vReturn.ToString());

                        }
                    }
                }
            }
        }
    }
}

 

* 폼 불러오기

* 클래스 함수 불러오기

 

* 예제 결과 화면

 

폼 불러오기 결과 화면

 

클래스 함수 불러오기 결과 화면

 

반응형
반응형

* VBNET 폴더 복사 예제...

 

메인 화면

전체 소스 코드

Form1.vb

 

Public Class Form1

    Private Sub button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles button1.Click
        '원본 폴더 열기
        Dim fbd As FolderBrowserDialog = New FolderBrowserDialog()

        If fbd.ShowDialog() = Windows.Forms.DialogResult.OK Then
            txtOriginFolder.Text = fbd.SelectedPath
        End If

    End Sub

    Private Sub button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles button2.Click
        '복사될 대상 위치 폴더 열기
        Dim fbd As FolderBrowserDialog = New FolderBrowserDialog()

        If fbd.ShowDialog() = Windows.Forms.DialogResult.OK Then
            txtCopyFolder.Text = fbd.SelectedPath
        End If

    End Sub

    Private Sub button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles button3.Click
        '폴더 복사
        If txtOriginFolder.Text = "" Or txtCopyFolder.Text = "" Then
            MessageBox.Show("원본 폴더 또는 복사 대상 폴더를 선택해 주세요.", "확 인", MessageBoxButtons.OK, MessageBoxIcon.Asterisk)
            Return
        End If

        button3.Text = "폴더 복사 중..."
        button3.Refresh()

        If FolderCopy(txtOriginFolder.Text, txtCopyFolder.Text) Then
            MessageBox.Show("폴더 복사가 완료 되었습니다.", "확 인", MessageBoxButtons.OK, MessageBoxIcon.Asterisk)
        Else
            MessageBox.Show("폴더 복사가 실패 하였습니다.", "확 인", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End If

        button3.Text = "폴더 복사"

    End Sub

    Private Function FileCopy(ByVal strOriginFile As String, ByVal strCopyFile As String) As Boolean

        Dim fi As System.IO.FileInfo = New System.IO.FileInfo(strOriginFile)
        Dim lSize As Long = 0
        Dim lTotalSize As Long = fi.Length
        '버퍼 사이즈 임의 지정...
        Dim bBuf(1024) As Byte

        '복사될 파일이 존재 한다면 삭제하고...
        If System.IO.File.Exists(strCopyFile) Then
            System.IO.File.Delete(strCopyFile)
        End If

        '원본 파일 열기...
        Using fsIn As System.IO.FileStream = New System.IO.FileStream(strOriginFile, IO.FileMode.Open, IO.FileAccess.Read, IO.FileShare.Read)
            '대상 파일 만들기...
            Using fsOut As System.IO.FileStream = New System.IO.FileStream(strCopyFile, IO.FileMode.Create, IO.FileAccess.Write)

                While (lSize < lTotalSize)
                    Try
                        Dim iLen As Integer = fsIn.Read(bBuf, 0, bBuf.Length)   '원본 파일 버퍼크기 만큼 읽기
                        lSize += iLen                                           '실제 원본 파일 읽어온 버퍼 갯수
                        fsOut.Write(bBuf, 0, iLen)                              '읽어온 버퍼만큼 대상 파일에 쓰기
                    Catch ex As Exception
                        fsOut.Flush()
                        fsOut.Close()
                        fsIn.Close()

                        '파일 복사 에러시 대상 파일은 일단 삭제...
                        If System.IO.File.Exists(strCopyFile) Then
                            System.IO.File.Delete(strCopyFile)
                        End If

                        Return False
                    End Try

                End While

                fsOut.Flush()
                fsOut.Close()
            End Using

            fsIn.Close()
        End Using

        Return True

    End Function

    Private Function FolderCopy(ByVal strOriginFolder As String, ByVal strCopyFolder As String) As Boolean
        '폴더가 없으면 만들기..
        If (Not System.IO.Directory.Exists(strCopyFolder)) Then
            System.IO.Directory.CreateDirectory(strCopyFolder)
        End If

        '파일 목록 불러오기...
        Dim strFiles() As String = System.IO.Directory.GetFiles(strOriginFolder)
        '폴더 목록 불러오기...
        Dim strFolders() As String = System.IO.Directory.GetDirectories(strOriginFolder)

        Try
            '파일 복사 부분...
            For Each strFile As String In strFiles
                Dim strName As String = System.IO.Path.GetFileName(strFile)
                Dim strDest As String = System.IO.Path.Combine(strCopyFolder, strName)

                '파일 복사
                FileCopy(strFile, strDest)

            Next

            For Each strFolder As String In strFolders
                Dim strName As String = System.IO.Path.GetFileName(strFolder)
                Dim strDest As String = System.IO.Path.Combine(strCopyFolder, strName)

                FolderCopy(strFolder, strDest)
            Next

        Catch ex As Exception
            Return False
        End Try
        
        Return True

    End Function

End Class

 

* 예제 결과

 

결과 화면

 

 

위 그림들은 테스트 결과 이미지들 입니다. 실제 복사가 정상적으로 이루어 졌는지 복사 하면서 잃게 된 용량은 없는지



https://kdsoft-zeros.tistory.com/50?category=846222

 

[VBNET] FileCopy (파일 복사 예제)

* VBNET 파일 복사 예제... 전체 소스 코드 Form1.vb Public Class Form1 '첫번째 방법... Private Sub button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles button1.Click Dim..

kdsoft-zeros.tistory.com

https://kdsoft-zeros.tistory.com/40?category=846222

 

[VBNET] 폴더 및 파일, 드라이브 사이즈 (Size) 구하기

* 폴더 및 파일, 드라이브 목록 및 사이즈 구하기 예제 File Open 버튼 : 파일 대화 상자가 뜨게 되며, 해당 파일 선택 시 위 그림과 같이 파일의 위치 와 사이즈가 표시 됩니다. 다만 사이즈 표시는 기본 Byte..

kdsoft-zeros.tistory.com

 

반응형
반응형

* 폴더 복사 예제...

 

메인 화면

전체 소스 코드

Form1.cs

 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace CSharp_FolderCopy
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //원본 폴더 열기...
            FolderBrowserDialog fbd = new FolderBrowserDialog();

            if (fbd.ShowDialog() == DialogResult.OK)
            {
                txtOriginFolder.Text = fbd.SelectedPath;
            }

        }

        private void button2_Click(object sender, EventArgs e)
        {
            //대상 폴더 열기...
            FolderBrowserDialog fbd = new FolderBrowserDialog();

            if (fbd.ShowDialog() == DialogResult.OK)
            {
                txtCopyFolder .Text = fbd.SelectedPath;
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            //폴더 복사...

            //원본 폴더 또는 복사 대상 폴더를 선택 하지 않았을 경우
            if (txtOriginFolder.Text == "" || txtCopyFolder.Text == "")
            {
                MessageBox.Show("원본 폴더 또는 복사 대상 폴더를 선택해 주세요.", "확 인", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                return;
            }

            button3.Text = "폴더 복사 중...";
            button3.Refresh();

            if (FolderCopy(txtOriginFolder.Text, txtCopyFolder.Text))
            {
                MessageBox.Show("폴더 복사가 완료 되었습니다.", "확 인", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
            }
            else
            {
                MessageBox.Show("폴더 복사가 실패 하였습니다.", "확 인", MessageBoxButtons.OK, MessageBoxIcon.Error );
            }

            button3.Text ="폴더 복사";
        }
        
        //파일 복사 함수
        private bool FileCopy(string strOriginFile, string strCopyFile)
        {
            System.IO.FileInfo fi = new System.IO.FileInfo(strOriginFile);
            long iSize = 0;
            long iTotalSize = fi.Length;
            //1024 버퍼 사이즈 임의로...
            byte[] bBuf = new byte[1024];

            //동일 파일이 존재하면 삭제 하고 다시하기 위해...
            if (System.IO.File.Exists(strCopyFile))
            {
                System.IO.File.Delete(strCopyFile);
            }

            //원본 파일 열기...
            System.IO.FileStream fsIn = new System.IO.FileStream(strOriginFile, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read);
            //대상 파일 만들기...
            System.IO.FileStream fsOut = new System.IO.FileStream(strCopyFile, System.IO.FileMode.Create, System.IO.FileAccess.Write);

            while (iSize < iTotalSize)
            {
                try
                {
                    int iLen = fsIn.Read(bBuf, 0, bBuf.Length);
                    iSize += iLen;
                    fsOut.Write(bBuf, 0, iLen);

                }
                catch (Exception ex)
                {
                    //파일 연결 해제...
                    fsOut.Flush();
                    fsOut.Close();
                    fsIn.Close();

                    //에러시 삭제...
                    if (System.IO.File.Exists(strCopyFile))
                    {
                        System.IO.File.Delete(strCopyFile);
                    }
                    return false;
                }

            }
            //파일 연결 해제...
            fsOut.Flush();
            fsOut.Close();
            fsIn.Close();

            return true;
        }

    
        private bool FolderCopy(string strOriginFolder, string strCopyFolder)
        {
            //폴더가 없으면 만듬...
            if (!System.IO.Directory.Exists(strCopyFolder))
            {
                System.IO.Directory.CreateDirectory(strCopyFolder);
            }

            //파일 목록 불러오기...
            string[] files = System.IO.Directory.GetFiles(strOriginFolder);
            //폴더 목록 불러오기...
            string[] folders = System.IO.Directory.GetDirectories(strOriginFolder);

            foreach (string file in files)
            {
                string name = System.IO.Path.GetFileName(file);
                string dest = System.IO.Path.Combine(strCopyFolder, name);
                //파일 복사 부분 넣기...
                FileCopy(file, dest);
            }

            // foreach 안에서 재귀 함수를 통해서 폴더 복사 및 파일 복사 진행 완료  
            foreach (string folder in folders)
            {
                string name = System.IO.Path.GetFileName(folder);
                string dest = System.IO.Path.Combine(strCopyFolder, name);
                FolderCopy(folder, dest);
            }


            return true;
        }

        

    }
}

폴더 복사 함수
파일 복사 함수

* 예제 결과

 

결과 화면

 

 

위 그림들은 테스트 결과 이미지들 입니다. 실제 복사가 정상적으로 이루어 졌는지 복사 하면서 잃게 된 용량은 없는지

 

* 참조 게시글

 

https://kdsoft-zeros.tistory.com/49?category=846221

 

[C#] File Copy (파일 복사 예제)

* 파일 복사 예제 전체 소스 코드 Form1.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text;..

kdsoft-zeros.tistory.com

https://kdsoft-zeros.tistory.com/39?category=846221

 

[C#] 폴더 및 파일, 드라이브 사이즈 (Size) 구하기

* 폴더 및 파일, 드라이브 목록 및 사이즈 구하기 예제 File Open 버튼 : 파일 대화 상자가 뜨게 되며, 해당 파일 선택 시 위 그림과 같이 파일의 위치 와 사이즈가 표시 됩니다. 다만 사이즈 표시는 기본 Byte..

kdsoft-zeros.tistory.com

 

반응형
반응형

* MD5 를 이용한 파일 체크섬 예제...

 

메인화면

전체 소스 코드

Form1.vb

 

Public Class Form1

    Private Sub button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles button1.Click
        Dim ofd As OpenFileDialog = New OpenFileDialog()

        '텍스트 파일만 열기...
        'ofd.Filter = "TXT File(*.txt)|*.txt"

        If ofd.ShowDialog() = Windows.Forms.DialogResult.OK Then

            '파일 내용을 byte 배열로 얻어 오기...
            Dim btAscii() As Byte = System.IO.File.ReadAllBytes(ofd.FileName)
            Dim btHash() As Byte = System.Security.Cryptography.MD5.Create().ComputeHash(btAscii)

            lblSourcePath.Text = ofd.FileName
            textBox1.Text = BitConverter.ToString(btHash).Replace("-", "").ToLower()


            If textBox2.Text <> "" Then
                If textBox1.Text = textBox2.Text Then
                    lbl.Text = "체크섬이 같습니다."
                Else
                    lbl.Text = "체크섬이 다릅니다."
                End If
            End If

        End If

    End Sub

    Private Sub button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles button2.Click
        Dim ofd As OpenFileDialog = New OpenFileDialog()

        '텍스트 파일만 열기...
        'ofd.Filter = "TXT File(*.txt)|*.txt"

        If ofd.ShowDialog() = Windows.Forms.DialogResult.OK Then

            '파일 내용을 byte 배열로 얻어 오기...
            Dim btAscii() As Byte = System.IO.File.ReadAllBytes(ofd.FileName)
            Dim btHash() As Byte = System.Security.Cryptography.MD5.Create().ComputeHash(btAscii)

            lblDestPath.Text = ofd.FileName
            textBox2.Text = BitConverter.ToString(btHash).Replace("-", "").ToLower()


            If textBox1.Text <> "" Then
                If textBox1.Text = textBox2.Text Then
                    lbl.Text = "체크섬이 같습니다."
                Else
                    lbl.Text = "체크섬이 다릅니다."
                End If
            End If

        End If
    End Sub

End Class

 

* 예제 결과

 

위 그림은 파일 안에 내용이 같았을 경우 만약 다르다면...

 

위 그림과 같이 체크섬이 다르게 표시 됩니다.

 

https://kdsoft-zeros.tistory.com/57

 

[C#] File CheckSum 예제 (MD5 Checksum)

* 파일 MD5 체크섬 예제... 전체 소스 코드 Form1.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using Syst..

kdsoft-zeros.tistory.com

 

반응형
반응형

* 파일 MD5 체크섬 예제...

 

메인화면

전체 소스 코드

Form1.cs

 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using System.Security.Cryptography;
using System.IO;

namespace CSharp_CheckSumFile
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();

            //텍스트파일만 열기...
            //ofd.Filter = "TXTFile(*.txt)|*.txt";


            if(ofd.ShowDialog() == DialogResult.OK)
            {
                //파일 내용을 byte 배열로 얻어 오기...
                byte[] btAscii = File.ReadAllBytes(ofd.FileName);
                byte[] btHash = MD5.Create().ComputeHash(btAscii);

                lblSourcePath.Text = ofd.FileName;
                textBox1.Text = BitConverter.ToString(btHash).Replace("-", "").ToLower();

                if (textBox2.Text != "")
                {
                    if (textBox1.Text == textBox2.Text)
                    {
                        lbl.Text = "체크섬이 같습니다.";
                    }
                    else
                    {
                        lbl.Text = "체크섬이 다릅니다.";
                    }
                }
            }

        }

        private void button2_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();

            //텍스트파일만 열기...
            //ofd.Filter = "TXTFile(*.txt)|*.txt";

            if (ofd.ShowDialog() == DialogResult.OK)
            {
                //파일 내용을 byte 배열로 얻어 오기...
                byte[] btAscii = File.ReadAllBytes(ofd.FileName);
                byte[] btHash = MD5.Create().ComputeHash(btAscii);

                lblDestPath.Text = ofd.FileName;
                textBox2.Text = BitConverter.ToString(btHash).Replace("-", "").ToLower();

                if (textBox1.Text != "")
                {
                    if (textBox1.Text == textBox2.Text)
                    {
                        lbl.Text = "체크섬이 같습니다.";
                    }
                    else
                    {
                        lbl.Text = "체크섬이 다릅니다.";
                    }
                }
            }
        }

    }
}

 

* 예제 결과

 

위 그림은 파일 안에 내용이 같았을 경우 만약 다르다면...

 

위 그림과 같이 체크섬이 다르게 표시 됩니다.

반응형

+ Recent posts