2017-10-24 14 views
0

이 코드를 참조하십시오.C#에서 파일 스트림을 닫는 방법

string name = dt.Rows[0]["Name"].ToString(); 
byte[] documentBytes = (byte[])dt.Rows[0]["DocumentContent"]; 

int readBytes = 0; 
//int index = 0; 
readBytes = documentBytes.Length; 
try 
{ 
    using (FileStream fs = new FileStream(name, FileMode.Create, FileAccess.Write, FileShare.Read)) 
    { 

     fs.Write(documentBytes, 0, readBytes); 
     //System.Diagnostics.Process prc = new System.Diagnostics.Process(); 
     //prc.StartInfo.FileName = fs.Name; 
     Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application(); 
     app.Visible = false; 
     Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Open(fs.Name); 
     Microsoft.Office.Interop.Excel._Worksheet worksheet = (Excel.Worksheet)workbook.Sheets[1]; // Explicit cast is not required here 
    // lastRow = worksheet.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell).Row; 

     app.Visible = true; 


     fs.Flush(); 
     fs.Close(); 
    } 
} 
catch (Exception ex) 
{ 
    MessageBox.Show("You have clicked more than one time. File is already open.", "WorkFlow", MessageBoxButtons.OK, MessageBoxIcon.Information); 
} 

파일 스트림을 사용하여 Excel 파일을 여는 중입니다. Excel이 멋지게 나타납니다. 하지만 파일 스트림을 닫을 수 없습니다. 여전히 'File Now available'이라는 작은 팝업이 나타납니다. 어떻게 그걸 없앨까요? fs.Close()와 Flush()가 실제로 여기서 작동하지 않는 것을 볼 수 있습니다. 도와주세요.

+0

"파일을 사용할 수 있습니까?" 그게 진짜 메시지 야? – Default

+1

Excel에서는 파일에 FileShare.Read를 사용했음을 알았으므로이 파일에 쓸 수없고 읽기 전용 모드로 파일을 열어야한다는 것을 알고 있습니다. 파일을 닫으면 다시 행복해진다. 따라서 해결 방법은 간단합니다. Excel을 시작하기 전에 파일 *을 닫습니다. –

+0

코드에는 스트림에 대해'using'과'Close'가 있습니다 - 둘 다 가지고 있어도 중복됩니다. –

답변

3

스트림을 열어 둔 상태에서 Excel에서 파일을 열 것을 요청하는 중입니다. 방금 바이트를 쓰려고하면 다음을 사용합니다.

// This will close the file handle after writing the data 
File.WriteAllBytes(name, documentBytes); 

// Then you're fine to get Excel to open it 
var app = new Microsoft.Office.Interop.Excel.Application(); 
app.Visible = false; 
var workbook = app.Workbooks.Open(name); 
+0

이름은 var workbook = app.Workbooks.Open (name);에서 작동하지 않습니다. –

+0

@SajithSudhi는 : 기본적으로 어떤 정보를 우리에게 제공하지 않습니다 "작동하지 않습니다"처리되지 않은 'System.Runtime.InteropServices.COMException'형식의 예외가 WorkFlowUAT.exe에 추가 정보를 발생 매우 어려운 당신에게 –

+0

도움을 만들기 : 죄송합니다 letter.xlsx를 찾을 수 없습니다. 이동되었거나 이름이 변경되었거나 삭제되었을 가능성이 있습니까? –