InfoPath 2003에서 Visual C#을 사용하여 프로그래밍 방식으로 파일 첨부 파일을 인코딩 및 디코딩하는 방법

요약

Microsoft Office InfoPath 2007 또는 Microsoft Office InfoPath 2003 SP1(서비스 팩 1)에서 파일 첨부 파일 컨트롤을 사용하여 InfoPath 양식 서식 파일에 파일을 첨부할 수 있습니다. 특정 상황에서는 파일 첨부 파일 컨트롤에 연결된 파일을 인코딩한 다음 디코딩할 수 있습니다. 이 경우 Microsoft Visual C#을 사용하여 인코더 클래스 및 디코더 클래스를 만들 수 있습니다. 그런 다음, 인코더 클래스와 디코더 클래스를 사용하여 파일 첨부 파일을 인코딩하고 디코딩할 수 있습니다.

소개

이 문서에서는 InfoPath 2003에서 Microsoft Visual C#을 사용하여 프로그래밍 방식으로 파일 첨부 파일을 인코딩하고 디코딩하는 방법을 소개합니다. InfoPath 2010 또는 InfoPath 2007에서 이 작업을 수행하는 방법에 대한 자세한 내용은 다음 웹 페이지를 참조하세요. InfoPath 2010 또는 InfoPath 2007에서 Visual C#을 사용하여 프로그래밍 방식으로 파일 첨부 파일을 인코딩하고 디코딩하는 방법 .

추가 정보

Microsoft에서 제공하는 프로그래밍 예제는 예시를 위한 것일 뿐이며 이와 관련하여 명시적이거나 묵시적인 어떠한 보증도 하지 않습니다. 이는 상품성이나 특정 목적에 대한 적합성의 묵시적인 보증을 포함하며 이에 제한되지 않습니다. 이 문서에서는 예제에 사용되고 있는 프로그래밍 언어와 프로시저를 만들고 디버깅하는 데 사용되는 도구를 사용자가 잘 알고 있는 것으로 가정합니다. Microsoft 지원 엔지니어는 사용자에게 도움이 되도록 특정 프로시저에 대한 기능을 설명할 수 있지만 사용자의 특정 요구 사항에 맞도록 예제를 수정하여 추가 기능을 제공하거나 프로시저를 구성하지는 않습니다.

Visual C# InfoPath 2003 프로젝트 만들기

  1. Microsoft Visual Studio .NET 2003을 시작합니다.

  2. [파일] 메뉴에서 [새로 만들기]를 클릭한 다음 [프로젝트]를 클릭합니다.

  3. 새 프로젝트 대화 상자의 Microsoft Office InfoPath Projects 폴더에서 Visual C# 프로젝트를 클릭합니다.

  4. 이름 상자에 AttachmentEncoding을 입력하고 확인을 클릭합니다.

  5. Microsoft Office 프로젝트 마법사에서 새 양식 서식 파일 만들기를 클릭한 다음 마침을 클릭합니다.

    Microsoft Office 프로젝트 마법사는 AttachmentEncoding이라는 새 Visual Studio .NET 2003 프로젝트를 만듭니다. InfoPath 양식 서식 파일도 만들어집니다. InfoPath 양식 서식 파일의 이름은 AttachmentEncoding입니다.

Visual Studio .NET 2003에서 인코더 클래스 만들기

  1. 솔루션 탐색기 AttachmentEncoding을 마우스 오른쪽 단추로 클릭하고 추가를 가리킨 다음 새 항목 추가를 클릭합니다.
  2. 새 항목 추가 대화 상자의 템플릿 창에서 클래스를 클릭하고 이름 상자에 InfoPathAttachmentEncoder.cs를 입력한 다음 열기를 클릭합니다.
  3. InfoPathAttachmentEncoder.cs 파일의 모든 코드를 다음 코드로 바꿉니다.
    using System;
    using System.IO;
    using System.Text;
    using System.Security.Cryptography;
    
    namespace InfoPathAttachmentEncoding
    {
    /// <summary>
    /// InfoPathAttachment encodes file data into the format expected by InfoPath for use in file attachment nodes.
    /// </summary>
    public class InfoPathAttachmentEncoder
    {
    private string base64EncodedFile = string.Empty;
    private string fullyQualifiedFileName;
    
    /// <summary>
    /// Creates an encoder to create an InfoPath attachment string.
    /// </summary>
    /// <param name="fullyQualifiedFileName"></param>
    public InfoPathAttachmentEncoder(string fullyQualifiedFileName)
    {
    if (fullyQualifiedFileName == string.Empty)
    throw new ArgumentException("Must specify file name", "fullyQualifiedFileName");
    
    if (!File.Exists(fullyQualifiedFileName))
    throw new FileNotFoundException("File does not exist: " + fullyQualifiedFileName, fullyQualifiedFileName);
    
    this.fullyQualifiedFileName = fullyQualifiedFileName;
    }
    
    /// <summary>
    /// Returns a Base64 encoded string.
    /// </summary>
    /// <returns>String</returns>
    public string ToBase64String()
    {
    if (base64EncodedFile != string.Empty)
    return base64EncodedFile;
    
    // This memory stream will hold the InfoPath file attachment buffer before Base64 encoding.
    MemoryStream ms = new MemoryStream();
    
    // Get the file information.
    using (BinaryReader br = new BinaryReader(File.Open(fullyQualifiedFileName, FileMode.Open, FileAccess.Read, FileShare.Read)))
    {
    string fileName = Path.GetFileName(fullyQualifiedFileName);
    
    uint fileNameLength = (uint)fileName.Length + 1;
    
    byte[] fileNameBytes = Encoding.Unicode.GetBytes(fileName);
    
    using (BinaryWriter bw = new BinaryWriter(ms))
    {
    // Write the InfoPath attachment signature. 
    bw.Write(new byte[] { 0xC7, 0x49, 0x46, 0x41 });
    
    // Write the default header information.
    bw.Write((uint)0x14);// size
    bw.Write((uint)0x01);// version
    bw.Write((uint)0x00);// reserved
    
    // Write the file size.
    bw.Write((uint)br.BaseStream.Length);
    
    // Write the size of the file name.
    bw.Write((uint)fileNameLength);
    
    // Write the file name (Unicode encoded).
    bw.Write(fileNameBytes);
    
    // Write the file name terminator. This is two nulls in Unicode.
    bw.Write(new byte[] {0,0});
    
    // Iterate through the file reading data and writing it to the outbuffer.
    byte[] data = new byte[64*1024];
    int bytesRead = 1;
    
    while (bytesRead > 0)
    {
    bytesRead = br.Read(data, 0, data.Length);
    bw.Write(data, 0, bytesRead);
    }
    }
    }
    
    // This memorystream will hold the Base64 encoded InfoPath attachment.
    MemoryStream msOut = new MemoryStream();
    
    using (BinaryReader br = new BinaryReader(new MemoryStream(ms.ToArray())))
    {
    // Create a Base64 transform to do the encoding.
    ToBase64Transform tf = new ToBase64Transform();
    
    byte[] data = new byte[tf.InputBlockSize];
    byte[] outData = new byte[tf.OutputBlockSize];
    
    int bytesRead = 1;
    
    while (bytesRead > 0)
    {
    bytesRead = br.Read(data, 0, data.Length);
    
    if (bytesRead == data.Length)
    tf.TransformBlock(data, 0, bytesRead, outData, 0);
    else
    outData = tf.TransformFinalBlock(data, 0, bytesRead);
    
    msOut.Write(outData, 0, outData.Length);
    }
    }
    
    msOut.Close();
    
    return base64EncodedFile = Encoding.ASCII.GetString(msOut.ToArray());
    }
    }
    }
    

Visual Studio .NET 2003에서 디코더 클래스 만들기

  1. 솔루션 탐색기 AttachmentEncoding을 마우스 오른쪽 단추로 클릭하고 추가를 가리킨 다음 새 항목 추가를 클릭합니다.
  2. 새 항목 추가 대화 상자의 템플릿 창에서 클래스를 클릭하고 이름 상자에 InfoPathAttachmentDecoder.cs를 입력한 다음 열기를 클릭합니다.
  3. InfoPathAttachmentDecoder.cs 파일의 모든 코드를 다음 코드로 바꿉니다.
    using System;
    using System.IO;
    using System.Text;
    
    namespace InfoPathAttachmentEncoding
    {
    /// <summary>
    /// Decodes a file attachment and saves it to a specified path.
    /// </summary>
    public class InfoPathAttachmentDecoder
    {
    private const int SP1Header_Size = 20;
    private const int FIXED_HEADER = 16;
    
    private int fileSize;
    private int attachmentNameLength;
    private string attachmentName;
    private byte[] decodedAttachment;
    
    /// <summary>
    /// Accepts the Base64 encoded string
    /// that is the attachment.
    /// </summary>
    public InfoPathAttachmentDecoder(string theBase64EncodedString)
    {
    byte [] theData = Convert.FromBase64String(theBase64EncodedString);
    using(MemoryStream ms = new MemoryStream(theData))
    {
    BinaryReader theReader = new BinaryReader(ms);
    DecodeAttachment(theReader);
    }
    }
    
    private void DecodeAttachment(BinaryReader theReader)
    {
    //Position the reader to get the file size.
    byte[] headerData = new byte[FIXED_HEADER];
    headerData = theReader.ReadBytes(headerData.Length);
    
    fileSize = (int)theReader.ReadUInt32();
    attachmentNameLength = (int)theReader.ReadUInt32() * 2;
    
    byte[] fileNameBytes = theReader.ReadBytes(attachmentNameLength);
    //InfoPath uses UTF8 encoding.
    Encoding enc = Encoding.Unicode;
    attachmentName = enc.GetString(fileNameBytes, 0, attachmentNameLength - 2);
    decodedAttachment = theReader.ReadBytes(fileSize);
    }
    
    public void SaveAttachment(string saveLocation)
    {
    string fullFileName = saveLocation;
    if(!fullFileName.EndsWith(Path.DirectorySeparatorChar))
    {
    fullFileName += Path.DirectorySeparatorChar;
    }
    
    fullFileName += attachmentName;
    
    if(File.Exists(fullFileName))
    File.Delete(fullFileName);
    
    FileStream fs = new FileStream(fullFileName, FileMode.CreateNew);
    BinaryWriter bw = new BinaryWriter(fs);
    bw.Write(decodedAttachment);
    
    bw.Close();
    fs.Close();
    }
    
    public string Filename
    {
    get{ return attachmentName; }
    }
    
    public byte[] DecodedAttachment
    {
    get{ return decodedAttachment; }
    }
    }
    }
    
    

InfoPath 양식에 파일 첨부 파일 컨트롤 및 텍스트 상자 컨트롤 추가

  1. AttachmentEncoding InfoPath 양식 서식 파일의 디자인 작업 창에서 컨트롤을 클릭합니다.
  2. [컨트롤] 작업창의 [삽입] 컨트롤 아래에서 [첨부 파일]을 클릭합니다.
  3. 파일 첨부 파일 컨트롤을 마우스 오른쪽 단추로 클릭한 다음 파일 첨부 파일 속성을 클릭합니다.
  4. 파일 첨부 파일 속성 대화 상자의 필드 이름 상자에AttachmentField를 입력하고 확인을 클릭합니다.
  5. 컨트롤 작업창에서 삽입 컨트롤 아래의 텍스트 상자를 클릭합니다.
  6. 텍스트 상자 컨트롤을 마우스 오른쪽 단추로 클릭한 다음 텍스트 상자 속성을 클릭합니다.
  7. 텍스트 상자 속성 대화 상자의 필드 이름 상자에AttachmentName을 입력하고 확인을 클릭합니다.

InfoPath 양식에 연결 단추 추가

  1. 컨트롤 작업창에서 컨트롤 삽입 아래의 단추를 클릭합니다.
  2. 새 단추 컨트롤을 마우스 오른쪽 단추 로 클릭한 다음 단추 속성을 클릭합니다.
  3. 단추 속성 대화 상자에서 레이블 상자에 첨부를 입력하고 ID 상자에 btnAttach를 입력한 다음 양식 코드 편집을 클릭합니다.
  4. btnAttach_OnClick 메서드에 다음 코드를 추가합니다.
    //Get a reference to the attachment node.
    IXMLDOMNode theAttachmentNode = thisXDocument.DOM.selectSingleNode("my:myFields/my:theAttachmentField");
    
    //Get a reference to the filename node.
    IXMLDOMNode fileNameNode = thisXDocument.DOM.selectSingleNode("my:myFields/my:theAttachmentName");
    //Get the text of the node.
    String fileName = fileNameNode.text;
    if(fileName.Length > 0)
    {
    //Encode the file and assign it to the attachment node.
    InfoPathAttachmentEncoding.Encoder myEncoder = new InfoPathAttachmentEncoding.Encoder(fileName);
    if(theAttachmentNode.attributes.getNamedItem("xsi:nil") != null)
    theAttachmentNode.attributes.removeNamedItem("xsi:nil");
    theAttachmentNode.text = myEncoder.ToBase64String();
    }
    
    

InfoPath 양식에 저장 단추 추가

  1. AttachmentEncoding InfoPath 양식 서식 파일로 전환합니다.
  2. 컨트롤 작업창에서 컨트롤 삽입 아래의 단추를 클릭합니다.
  3. 새 단추 컨트롤을 마우스 오른쪽 단추 로 클릭한 다음 단추 속성을 클릭합니다.
  4. 단추 속성 대화 상자에서 레이블 상자에 저장을 입력하고 ID 상자에 btnSave를 입력한 다음 양식 코드 편집을 클릭합니다.
  5. btnSave _OnClick 메서드에 다음 코드를 추가합니다.
    //Get a reference to the attachment node.
    IXMLDOMNode n = thisXDocument.DOM.selectSingleNode("my:myFields/my:theAttachmentField");
    //Get the text of the node.
    String theAttachment = n.text;
    if(theAttachment.Length > 0)
    {
    InfoPathAttachmentEncoding.Decoder myDecoder = new InfoPathAttachmentEncoding.Decoder(theAttachment);
    myDecoder.SaveAttachment(@"<Path to save the file>");
    }
    
    

참고

이 코드에서 파일을 저장할 위치로 바꿉 있습니다.

InfoPath 양식 서식 파일이 완전히 신뢰할 수 있는지 확인

이 양식을 테스트하려면 InfoPath 양식 서식 파일을 완전히 신뢰할 수 있어야 합니다. 다음 방법 중 하나를 사용하여 InfoPath 양식 서식 파일이 완전히 신뢰할 수 있는지 확인할 수 있습니다.

  • Microsoft .NET Framework 1.1 구성 유틸리티를 사용하여 Visual C# 코드에만 전체 신뢰 권한을 부여합니다.

  • InfoPath SDK(소프트웨어 개발 키트)의 RegForm 유틸리티를 사용하여 양식을 완전히 신뢰할 수 있는 양식으로 만듭니다. 그러면 Visual C# 코드에 대한 전체 신뢰 권한이 부여됩니다.

  • 코드 서명 인증서를 사용하여 양식 서식 파일(.xsn)에 디지털 서명합니다. 코드 서명 인증서를 사용하여 양식 서식 파일의 디지털 서명을 하면 양식을 열 때 양식을 신뢰하라는 메시지가 사용자에게 표시됩니다. 이렇게 하면 폼을 완전히 신뢰할 수 있습니다. 따라서 Visual C# 코드에 완전 신뢰 권한이 부여됩니다.

  • InfoPath SDK의 IPFullTrust 매크로를 사용하여 양식을 완전히 신뢰할 수 있는 양식으로 만듭니다. IPFullTrust 매크로는 전체 신뢰를 위해 InfoPath 프로젝트의 매니페스트 파일(.xsf) 및 양식 서식 파일 설정을 자동화한 다음 IPFullTrust 매크로가 양식 서식 파일을 자동으로 등록합니다.

    매크로를 설치하고 사용하는 방법에 대한 자세한 내용은 다음 MSDN(Microsoft Developer Network) 웹 사이트를 참조하세요.

    https://msdn.microsoft.com/en-us/library/aa202736(office.11).aspx

  • InfoPath에서 외부 자동화를 사용하여 RegisterSolution 메서드를 호출합니다. 일반적으로 이 메서드는 등록된 양식이 개별 컴퓨터에만 등록되므로 양식 개발에만 사용됩니다. 추가 양식의 경우 다른 사용자는 자신의 컴퓨터에 추가 양식을 등록해야 합니다. 추가 양식에는 이 메서드를 사용하지 않는 것이 좋습니다. 양식을 게시할 때 이전 메서드 중 하나를 사용하는 것이 좋습니다.

이 양식은 양식 개발 중이므로 마지막 메서드를 사용할 수 있습니다. 이렇게 하려면 AttachmentEncoding InfoPath 양식 서식 파일을 찾은 다음 다음 단계를 수행합니다.

  1. 도구 메뉴에서 양식 옵션을 클릭합니다.

  2. 보안 탭을 클릭합니다.

  3. 양식의 디자인(권장) 확인란에 따라 자동으로 확인 확인란을 선택 취소하려면 클릭합니다.

    참고 InfoPath는 완전 신뢰 권한이 필요한 비즈니스 논리를 자동으로 검색할 수 없습니다. 따라서 완전 신뢰 권한을 명시적으로 부여해야 합니다.

  4. 전체 신뢰를 클릭한 다음 확인을 클릭합니다.

  5. AttachmentEncoding InfoPath 양식 서식 파일을 닫습니다. 변경 내용을 저장하라는 메시지가 표시되면 [예]를 클릭합니다.

    참고 Visual Studio .NET 2003 프로젝트를 닫지 마세요.

  6. Visual Studio .NET 2003에서 솔루션 탐색기 Manifest.xsf 파일을 두 번 클릭합니다. Manifest.xsf 파일이 열립니다.

  7. 루트 노드에서 publishUrl 특성을 찾습니다. publishUrl 특성 및 publishUrl 특성의 값을 제거합니다.

  8. 변경 내용을 저장한 다음 Manifest.xsf 파일을 닫습니다.

  9. 시작을 클릭하고 실행을 클릭하고 메모장을 입력한 다음 확인을 클릭합니다.

  10. 빈 텍스트 파일에 다음 코드를 추가합니다.

    oApp = WScript.CreateObject("InfoPath.ExternalApplication");
    strAbsolutePath = "<project_folder_url>\\Manifest.xsf";
    oApp.RegisterSolution(strAbsolutePath,"overwrite"); 
    
    

    참고 이 코드에서 project_folder_url 프로젝트 폴더의 Manifest.xsf 파일 경로로 바꿉니다. Manifest.xsf 파일의 경로를 이스케이프해야 합니다. 경로의 모든 단일 백슬라시(\)를 두 개의 백슬라시(\\)로 바꿔야 합니다.

  11. 컴퓨터에 Manifest.xsf 파일을 Register.js 파일로 저장합니다.

  12. RegisterSolution 메서드를 호출하려면 만든 Register.js 파일을 두 번 클릭합니다.

양식 테스트

  1. AttachmentEncoding Visual Studio .NET 2003 프로젝트에서 디버그 메뉴에서 시작을 클릭합니다. 그러면 InfoPath 양식이 미리 보기 모드로 시작됩니다.

  2. InfoPath 양식에서 텍스트 상자에 첨부할 파일의 경로를 입력한 다음 첨부를 클릭합니다.

    참고파일 첨부 파일 컨트롤을 두 번 클릭하여 파일이 올바르게 인코딩되었는지 확인합니다.

  3. 저장을 클릭합니다. "InfoPath 양식에 저장 단추 추가" 섹션에서 제공한 경로를 찾습니다.

  4. 테스트를 종료하려면 미리 보기 닫기를 클릭합니다.

참조

파일 첨부 파일 헤더 형식에 대한 자세한 내용은 다음 MSDN 웹 사이트를 참조하세요.

InfoPath 2003에서 파일 첨부 https://msdn.microsoft.com/en-us/library/aa168351(office.11).aspx