2016-10-03 2 views
0

내 프로그램은 특정 Excel 파일을 이미지 (SVG 형식)로 다른 폴더로 내 보내야합니다. 이는 CopyAndSaveTo 및 ExportRangeAsImage 메소드로 수행 할 수 있으며 작업을 수행합니다. MainWindow에는 클릭 할 때이 두 기능을 수행하는 버튼이 있습니다. 이 버튼을 클릭 한 사용자에게 진행률 (진행률 막대)을 알려주고 (복사 + 내보내기)이 과정을 원합니다. 가 나는 경우 BackgroundWorker를 사용하여 실현하기 위해 노력하고 내가 (메서드 ExportRangeAsImage에서) 다음 코드 주석 경우에만 작동 :업데이트 progressbar + backgroundworker가있는 clipboard.getimage() - WPF C#

Bitmap image = new Bitmap(System.Windows.Forms.Clipboard.GetImage()); 
image.Save(ImagePath + Path.GetFileNameWithoutExtension(file) + ".svg"); 
그렇지 않으면

나는 다음과 같은 오류 메시지 ( 독일에서 번역) 얻을 :

System.NullReferenceException에서 "System.Drawing.dll"형식의 예외가 발생했지만 사용자 코드에서 처리되지 않았습니다. 추가 정보 : 개체 참조가 개체 인스턴스로 설정되지 않았습니다. 이 예외 처리기를 사용할 수 있으면 프로그램이 계속 안전하게 실행될 수 있습니다.

private void UpdateDataOfLine1(object sender, ExecutedRoutedEventArgs e) 
     { 
      string[] files = Directory.GetFiles(RootPath); 
  
      BackgroundWorker worker = new BackgroundWorker(); 
      worker.WorkerReportsProgress = true; 
      worker.DoWork += worker_DoWork; 
      worker.ProgressChanged += worker_ProgressChanged; 
      worker.RunWorkerAsync(); 
     } 
  

  
     void worker_DoWork(object sender, DoWorkEventArgs e) 
     { 
      string[] files = Directory.GetFiles(RootPath); 
  
      for (int i = 0; i < files.Length; i++) 
      { 
       if (files[i].Contains("$") || files[i].Contains("~") || files[i].Contains("Thumb")) 
       { 
        continue; 
       } 
  
       File.Copy(files[i], DestPath + Path.GetFileName(files[i]), true); 
  
       string newFile = DestPath + Path.GetFileName(files[i]); 
  
       ExPortRangeAsImage(newFile); 
  
       (sender as BackgroundWorker).ReportProgress(i); 
       Thread.Sleep(100); 
      } 
     } 
  

  
     void worker_ProgressChanged(object sender, ProgressChangedEventArgs e) 
     { 
      Status.Value = e.ProgressPercentage; 
     } 
  

     public void ExPortRangeAsImage(string file) 
     { 
      var ExcelApp = new Microsoft.Office.Interop.Excel.Application(); 
  
      try 
      { 
       if (file.Contains("BeispielDatei")) 
       { 
        Workbook wb = ExcelApp.Workbooks.Open(file); 
        Worksheet ws = (Worksheet)wb.Sheets[1]; 
        Range range = ws.Range["A1:U35"]; 
        range.CopyPicture(XlPictureAppearance.xlScreen, XlCopyPictureFormat.xlBitmap); 
        wb.Close(SaveChanges: false); 
        Marshal.ReleaseComObject(wb); 
       } 
  
       else 
       { 
        Workbook wb = ExcelApp.Workbooks.Open(file); 
        Worksheet ws = (Worksheet)wb.Sheets[1]; 
        Range range = ws.Range["A1:U35"]; 
        range.CopyPicture(XlPictureAppearance.xlScreen, XlCopyPictureFormat.xlBitmap); 
        wb.Close(SaveChanges: false); 
        Marshal.ReleaseComObject(wb); 
       } 
      } 
  
      finally 
      { 
       Bitmap image = new Bitmap(System.Windows.Forms.Clipboard.GetImage()); 
       image.Save(ImagePath + Path.GetFileNameWithoutExtension(file) + ".svg"); 
  
       Marshal.ReleaseComObject(ExcelApp); 
      } 
     } 

당신은 내가 잘못 뭘하는지 아니면 내가 그것을 실현하는 방법을 나에게 보여줄 수 : 여기

전체 코드? BackgroundWorker 이외의 다른 방법이 있습니까?

도움을 주셔서 감사합니다. 여기

는 오류

+0

System.NullReferenceException이 발생할 때 중지를 설정할 수 있으며 어떤 코드가 아닌지 알 수 없습니다. – lindexi

+0

오류 스크린 샷을 추가했습니다 ... – Guilian

+0

'image' 개체 또는'ImagePath'가이 두 줄에서 null인지 확인하십시오? – AnjumSKhan

답변

0

당신은 스택 추적을 검토해야합니다의 스크린 샷이다, 나는 당신의 내부 예외 인해 크로스 스레드 액세스 위반 가능성이 높습니다 생각합니다.

NULL 참조가 아마도 null을 반환하는 System.Windows.Forms.Clipboard.GetImage() 때문에 트리거되고있는 중입니다.

당신은 UI 발송자 스레드에서이 부분을 실행 시도 할 수 있습니다 :이 또한 대부분 (복사 및 붙여 넣기 사이에 인종) 동기화 문제를 소개합니다

Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(()=> 
{ 
    Bitmap image = new Bitmap(System.Windows.Forms.Clipboard.GetImage()); 
    image.Save(ImagePath + Path.GetFileNameWithoutExtension(file) + ".svg"); 
} 

. 다른 이미지를 클립 보드로 복사하기 전에 이미지 쓰기가 완료되도록 코드를 재구성해야 할 수 있습니다.

+0

감사합니다 그것은 당신의 코드와 함께 작동 :)! – Guilian

+0

작업이 백그라운드에서 작업을 수행 할 때'System.Windows.Forms.Clipboard'를 사용할 수 있습니까? @loopedcode – lindexi

+0

하지만 UI 동기화 컨텍스트를 사용해야합니다. 여기에 예제를 참조하십시오. https://blogs.msdn.microsoft.com/csharpfaq/2010/06/18/parallel-programming-task-schedulers-and-synchronization-context/ – loopedcode