[C#] 파일 쓰기

C#은 파일 쓰기 간단하다 


using System.IO;




string MyFile = @"data.txt";

            string buf = "Hi Hello 안녕";

StreamWriter FW = File.CreateText(MyFile);

            

FW.WriteLine(buf);

            

FW.Close();


'and so on > c#' 카테고리의 다른 글

.NetFramework 설치 확인 하기  (0) 2013.01.17
C# PPT 내용 읽기  (0) 2013.01.15
c# 오피스 참조한 프로젝트 배포 시 필요한 dll  (0) 2013.01.07
c#dll c++에서 사용  (2) 2013.01.02
C++ DLL 함수 char*를 C#에서 읽어 오기  (0) 2012.09.26

.NetFramework 설치 확인 하기

각 버전별로 설치 되어있을경우 레지스트리 경로가 요기잉네?

http://support.microsoft.com/kb/318785/ko



=> 레지스트리 값을 읽어서 닷넷 프레임워크 설치 유무를 알 수 있음


-C# 버전 

http://msdn.microsoft.com/ko-kr/library/hh925568.aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-1

ㅎㅎㅎㅎ나는 C++이 필요하다고 


/////////////////////////////////////////////////////////////////////////

4- 클라이언트 

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Client

4전체 

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full

3.5 

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP\v3.5

3.0 

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP\v3.0\Setup

2.0 

HKEY_LOCAL_MACHINE\Software\Microsoft\NET Framework Setup\NDP\v2.0.50727


2.0, 3.0 3.5 서비스팩과 릴리즈 

원래 릴리즈의 경로를 가지고 있고, 값도 같음 (이름 : 설치, 형식 : REG_DWORD 데이터 : 1)


1.0은 원래 릴리즈 설치 경로 같고, 값이 다름

1.1은 64비트 32비트 설치 경로 다름 

'and so on > c#' 카테고리의 다른 글

[C#] 파일 쓰기  (0) 2013.01.18
C# PPT 내용 읽기  (0) 2013.01.15
c# 오피스 참조한 프로젝트 배포 시 필요한 dll  (0) 2013.01.07
c#dll c++에서 사용  (2) 2013.01.02
C++ DLL 함수 char*를 C#에서 읽어 오기  (0) 2012.09.26

C# PPT 내용 읽기

          PowerPoint.Application PowerPoint_App = new PowerPoint.Application();

            PowerPoint.Presentations multi_presentations = PowerPoint_App.Presentations;

            PowerPoint.Presentation presentation = multi_presentations.Open(@"C:\test - 복사본.pptx");

           

            string presentation_text = "";

            

            for (int i = 0; i < presentation.Slides.Count; i++)

            {

                foreach (var item in presentation.Slides[i + 1].Shapes)

                {

                    var shape = (PowerPoint.Shape)item;

                    if (shape.HasTextFrame == MsoTriState.msoTrue)

                    {

                        if (shape.TextFrame.HasText == MsoTriState.msoTrue)

                        {

                            var textRange = shape.TextFrame.TextRange;

                            var text = textRange.Text;

                            presentation_text += text + " ";

                            textBox1.Text = presentation_text;

                        }

                    }

                }

            }

            PowerPoint_App.Quit();

            Console.WriteLine(presentation_text);



ppt 는 문제가 많다 

'and so on > c#' 카테고리의 다른 글

[C#] 파일 쓰기  (0) 2013.01.18
.NetFramework 설치 확인 하기  (0) 2013.01.17
c# 오피스 참조한 프로젝트 배포 시 필요한 dll  (0) 2013.01.07
c#dll c++에서 사용  (2) 2013.01.02
C++ DLL 함수 char*를 C#에서 읽어 오기  (0) 2012.09.26

c# 오피스 참조한 프로젝트 배포 시 필요한 dll

Microsoft.Office.Interop.Excel.DLL

 위치 : C:\Program Files\Microsoft Visual Studio 10.0\Visual Studio Tools for Office\PIA\Office14


Microsoft.Office.Interop.Word.dll

 위치 : C:\Program Files\Microsoft Visual Studio 10.0\Visual Studio Tools for Office\PIA\Office14


Microsoft.Vbe.Interop.dll

 위치 : C:\Program Files\Microsoft Visual Studio 10.0\Visual Studio Tools for Office\PIA\Office14


office.dll

 위치 : C:\Program Files\Microsoft Visual Studio 10.0\Visual Studio Tools for Office\PIA\Office14


stdole.dll

 위치 : C:\Program Files\Microsoft Visual Studio 10.0\Visual Studio Tools for Office\PIA\Common


파워포인트는 내가 안써서 지움




vs가 설치되어 있지 않을 때 필요한 dll

msvcp100.dll

 위치 : C:\Program Files\Microsoft Visual Studio 10.0\VC\redist\x86\Microsoft.VC100.CRT

msvcr100.dll

 위치 : C:\Program Files\Microsoft Visual Studio 10.0\VC\redist\x86\Microsoft.VC100.CRT


dll 알아 내려고 설치 프로젝트까지 생성했다




* 나는 dll 생성하여서 오피스 관련 dll이 같이 안생겼는데

exe 파일로 생성하면 debug, release 폴더에 저 dll도 생기는 것 같음



*오피스 참조시에는 개발한 PC의 오피스와 

 사용될 PC의 오피스 고려해야 함

따라서 참조 시에 COM 탭에서 오피스 추가하는 것이 아닌

.NET 탭에서 해줌

'and so on > c#' 카테고리의 다른 글

.NetFramework 설치 확인 하기  (0) 2013.01.17
C# PPT 내용 읽기  (0) 2013.01.15
c#dll c++에서 사용  (2) 2013.01.02
C++ DLL 함수 char*를 C#에서 읽어 오기  (0) 2012.09.26
C# - Excel 내용 읽어오기  (0) 2012.09.17

c#dll c++에서 사용

- c#


using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;


using System.Runtime.InteropServices;


namespace MyEngin

{

    [Guid("DBE0E8C4-1C61-41f3-B6A4-4E2F353D3D05")]

    public interface IManagedInterface

    {

        int add(int a, int b);

        int printHi();

    }

    [Guid("C6659361-1625-4746-931C-36014B146679")]

    public class InterfaceImplementation : IManagedInterface

    {

        public int add(int a, int b)

        {

            return a + b;

        }

        public int printHi()

        {

            Console.WriteLine("안녕");

            return 1;

        }

    }

}


속성 

응용 프로그램 -> 어셈블리 정보-> 어셈블리를 COM에 노출 체크

빌드->COM Interop 등록 체크



visual studio 명령 프롬프트

regasm MyEngin.dll /tlb MyEngin.tlb


- c++



#include <Windows.h>

#include <stdio.h>


#pragma warning (disable: 4278)


#import "MyEngin.tlb" no_namespace named_guids



void main()

{

IManagedInterface *csi=NULL; 


   CoInitialize(NULL);


   HRESULT hr = CoCreateInstance(CLSID_InterfaceImplementation,NULL,CLSCTX_INPROC_SERVER,IID_IManagedInterface,reinterpret_cast<void**>(&csi));

   int a=GetLastError();

   if(SUCCEEDED(hr))

   {

  int b=csi->add(2,3); //C# dll에 있는 함수

  

  printf("%d\n", b);

  csi->printHi();

  getchar();

  CoUninitialize();

   }


}



* GUID는 

C:\Program Files\Microsoft SDKs\Windows\v7.0A\bin\NETFX 4.0 Tools\guidgen.exe로 생성 가능하다


 * 다른 PC에서 dll 사용 시 regasm 이용하여 tlb 등록하여야 함


* CoCreateInstance()에서 0x80070002 에러 발생 시

regasm MyEngin /codebase 한 후 

c++에서 빌드 하면 됌



C++ DLL 함수 char*를 C#에서 읽어 오기

- C++에서 만든 dll 함수 


extern "C" __declspec(dllexport) char* Suma(char* a, char*b)

{

char* result = (char*)LocalAlloc(LPTR, strlen(a) + strlen(b) +1);

strcat(result, a);

strcat(result, b);

  LocalFree(result);

return result;

}






- C#에서 dll함수 적용하기

class Program

{


 [DllImport("C:\\DllName.dll", CallingConvention = CallingConvention.Cdecl)]

public static extern System.IntPtr Suma(string a, string b);


static void Main()

{

string a = "a";

string b = "b";

IntPtr p = Suma(a,b);

string c = Marshal.PtrToStringAnsi(p);

Marshal.FreeHGlobal(p);

Console.WriteLine(c);

}

}




C++ 에서는 

LocalAlloc을 이용 메모리 할당 해줘야 함


C#에서는

 IntPtr 구조체를 선언하여 dll 함수 저장 후 

Marshal.PtrToStringAnsi() 메소드 이용하여 관리되는 string,  관리되지 않는 ANSI 문자열 복사 

Marshal.FreeHGlobal() 메소드 이용하여 할당한 메모리 해제 






 출처 - http://blog.naver.com/PostView.nhn?blogId=nickpooh&logNo=50108296076&redirect=Dlog&widgetTypeCall=true

C# - Excel 내용 읽어오기

Excel 내용을 읽는 것을 하고 있는데

Excel. range범위를


range = ESheet.get_Range("A1", missing); //A1 셀 선택 

range = range.get_Resize(5,5) // A1부터 5,5의 크기 


이런 식으로 설정 해줘야 해서.

이런 식으로는 텍스트를 읽어 올 수 있는데 

내가 모든 EXCEL 파일의 셀의 크기를 알 수 없어서 

읽어 오는 파일 마다 셀의 크기가 다른데 그럴 땐 어떻게 해야 하나 

하루 종일 찾았다 ㅜㅜ


(엑셀에서 셀이 만들어 질 수 있는 크기까지 찾아서 모든 크기안에 있는 내용을 찾으려고 했는데

데이터가 너무 커서 오버플로우 남 ㅋ  1048576 x 16384)


셀에 대한 메서드가 따로 있어서 

range를 설정 해 줄때 사용된 범위에 있는 마지막 셀을 이용하여 

아무 엑셀 파일을 선택하면 텍스트를 읽어 올 수 있게 설정해 주었다.


      public string ReadExcel(string path)

        {

           string filename = path;// string filename = "C:\\test.xlsx";

            object missing = System.Reflection.Missing.Value;


            Excel.Application EApp = new Excel.Application();


            Excel.Workbook EBook;

            Excel.Workbooks EBooks;


            Excel.Sheets ESheets;

            Excel._Worksheet ESheet;


            Excel.Range range;


            EApp.Visible = false;

//          EApp.WindowState = Excel.XlWindowState.xlMinimized;


            EBooks = EApp.Workbooks;

            EBook = EApp.Workbooks.Open(filename, missing, missing, missing, missing, missing, missing

               , missing, missing, missing, missing, missing, missing, missing, missing);

            

            ESheets = EBook.Worksheets;

            ESheet = (Excel._Worksheet)EBook.ActiveSheet;

            ESheet = (Excel._Worksheet)ESheets.get_Item(1);


            range = ESheet.get_Range("A1").SpecialCells(Excel.XlCellType.xlCellTypeLastCell);


           long row = range.Row;

            long column = range.Column;

            

String valueString = "";


            for (long rowCounter = 1; rowCounter <= row; rowCounter++)

            {

                for (long colCounter = 1; colCounter <= column; colCounter++)

                {

                    Excel.Range cell = (Excel.Range)ESheet.Cells[rowCounter, colCounter];


                    if (cell.Value == null)

                        valueString = string.Concat(valueString, " ");

                    else

                    {

                        valueString = string.Concat(valueString, cell.Value.ToString() + ",");

                        Console.Write(valueString);

                    }

                        textBox1.Text = valueString;


                }

                valueString = String.Concat(valueString,"\r\n");


            }




================================================================================
저 위의 함수를 이용해서 그동안 엑셀을 읽어 왔는데, 
데이터가 너무 클 경우에는 읽는 속도가 10분이 넘어감...ㅋㅋ( 2중 for문 때문인가ㅜㅜ )

그래서 새로운 방법을 알아 냄 
DataTable을 이용하여서 DataTable에 값을 저장 -> 이 부분이 진짜 빠름

나는 필요한게 String 형이여서 row[Col].ToString()으로 변환 해준다 

그래도 이전보다는 빨라졌당 1분 30초 정도 


using System.Data.OleDb;


      public string ReadExcel(string strFilePath)
        {
            // 엑셀 문서 내용 추출
            object missing = System.Reflection.Missing.Value;
            String valueString = "";

            string strProvider = string.Empty;
            strProvider = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" + strFilePath + @";Extended Properties=Excel 12.0";

            OleDbConnection excelConnection = new OleDbConnection(strProvider);
            excelConnection.Open();

            string strQuery = "SELECT * FROM [Sheet1$]";

            OleDbCommand dbCommand = new OleDbCommand(strQuery, excelConnection);
            OleDbDataAdapter dataAdapter = new OleDbDataAdapter(dbCommand);

            DataTable dTable = new DataTable();
            dataAdapter.Fill(dTable);

            // dTable에 추출된 내용을 String으로 변환
            foreach (DataRow row in dTable.Rows)
            {
                foreach (DataColumn Col in dTable.Columns)
                {
                    valueString += row[Col].ToString() + " ";
                }
            }
        
            dTable.Dispose();
            dataAdapter.Dispose();
            dbCommand.Dispose();

            excelConnection.Close();
            excelConnection.Dispose();

            return valueString;
        }







- 참고 

NamedRange.SpecialCells 메서드

셀에 대한 내용
http://technet.microsoft.com/ko-kr/subscriptions/microsoft.office.tools.excel.namedrange.specialcells

C# - Excel 창 접근하기

Application -> Books -> Book -> Sheets -> Sheet  순으로 설정 





        private void button1_Click(object sender, EventArgs e)

        {

            string filename = "C:\\test.xlsx";

            object missing = System.Reflection.Missing.Value;


            Excel.Application EApp;

            Excel.Workbook EBook; 


            Excel.Workbooks EBooks;

            Excel.Sheets ESheets;

            Excel._Worksheet ESheet;


            EApp = new Excel.Application();

            EApp.Visible = false;


            EBooks = EApp.Workbooks;

            EBook = EApp.Workbooks.Open(filename, missing, missing, missing, missing, missing, missing

                , missing, missing, missing, missing, missing, missing, missing, missing);

            ESheets = EBook.Worksheets;

            ESheet = (Excel._Worksheet)ESheets.get_Item(1);


//         Range 설정 해줘야 함 

.

.

.

.

.

.

.

.

.

.

.

.

.

.

//아래 적어주면 지금 작업중인(filename에 해당하는) 엑셀 창이 뜬다.


                EApp.Visible = true;

                EApp.UserControl = true;



}

C# - 파일 선택 다이얼로그 띄우기





            OpenFileDialog ofd = new OpenFileDialog();


            ofd.Filter = "모든 파일 (*.*) | *.*";

            ofd.ShowDialog();


            string path = ofd.FileName;

            textPathName.Text = ofd.FileName;



1. ofd.Filter에는 다이얼로그 창에 나오는 파일 종류 선택 할 수 있다  

예를들어 MS워드파일만 다이얼로그 창에 나오게 하고 싶으면 

ofd.Filter =  "WodrDocuments(*.doc) | *.doc";


2. textPathName은 내가 도구상자에서 만들어 준 textBox 이름 이어서 

textPathName.Text 하여 string을 지정할 경우 해당하는 string이 textbox에 표시된다.