2012-08-23 8 views
2

나는 CSV로 SQL을 전송하는 코드가 있습니다 그 후C#을, 파일을 액세스 할 수 없습니다

public void CreateCSVFile(DataTable dt, string strFilePath, bool Is_Ordre, int TypeDonne) 
{ 

    //FileStream fs = new FileStream(strFilePath, FileMode.Create); 
    // FileStream fs = File.Create(strFilePath); 

    // Create the CSV file to which grid data will be exported. 
    //StreamWriter sw = new StreamWriter(fs); 
    //StreamWriter sw = new StreamWriter(strFilePath, false); 
    using (var sw = new StreamWriter(strFilePath, false)) 
    { 
     // First we will write the headers. 
     //DataTable dt = m_dsProducts.Tables[0]; 
     int iColCount = dt.Columns.Count; 
     for (int i = 0; i < iColCount; i++) 
     { 
      sw.Write(dt.Columns[i]); 
      if (i < iColCount - 1) 
      { 
       sw.Write(","); 
      } 
     } 
     if (Is_Ordre) sw.Write(", TYP_DONNE"); 

     sw.Write(sw.NewLine); 

     // Now write all the rows. 
     foreach (DataRow dr in dt.Rows) 
     { 
      for (int i = 0; i < iColCount; i++) 
      { 
       if (!Convert.IsDBNull(dr[i])) 
       { 
        sw.Write("\'" + dr[i].ToString().Replace("'", " ").Replace(",", ".") + "\'"); 
       } 
       else 
       { 
        sw.Write("\' \'"); 
       } 
       if (i < iColCount - 1) 
       { 
        sw.Write(","); 
       } 
      } 
      if (Is_Ordre) sw.Write(", \'" + TypeDonne + "\'"); 
      sw.Write(sw.NewLine); 
     }     
     sw.Flush(); 
     sw.Close(); 
     sw.Dispose(); 
    } 
     //fs.Close(); 

} 

내가 이메일을 통해 CSV 파일을 보내

Attachment data_OD = new Attachment(LeSource, MediaTypeNames.Application.Octet); 
Attachment data_LV = new Attachment(LeSource_LV, MediaTypeNames.Application.Octet); 
oEmail.SendingEmail(ClientID, data_OD, data_LV); 

public void SendingEmail(string CodeClient, Attachment dataOD, Attachment dataLV) 
{ 
    try 
    { 
     Pers_Conf oConf = LeConf.Get_Config(CodeClient); 

     MailMessage omail = new MailMessage(); 
     var oSmtp = new SmtpClient("smtp.gmail.com", 587) 
     { 
      Credentials = new NetworkCredential("[email protected]", "xxxxxx"), 
      EnableSsl = true 
     }; 

     omail.From = new MailAddress("[email protected]");    
     omail.To.Add(oConf.EmailAddr); 
     omail.Subject = "xxxxxx_" + CodeClient; 
     omail.Body = CodeClient; 

     omail.Attachments.Add(dataOD); 
     omail.Attachments.Add(dataLV); 

     oSmtp.Send(omail); 
    } 
    catch (Exception excThrown) 
    { 
     throw excThrown; 
    } 

StreamWriter 제대로 파일을 닫습니다하지 않습니다, 난 이미이 함께 시도 것 같다 :

Try 
    { 
    StreamWriter sw = new StreamWriter(strFilePath, false); 
    } 
    Catch 
    { 
    } 
    Finaly 
    { 
    sw.Flush(); 
    sw.Close(); 
    sw.Dispose(); 
} 

만에를 finally 블록이 인식되지 않습니다. sw.

아이디어가 있으십니까?

추신 :이 코드 줄은 파일이 다른 프로세스

using (var sw = new StreamWriter(strFilePath, false)) 

때문에 StreamWriter 제대로 가깝거나 이메일 보내기가이 파일을 사용하고 있기 때문에하지의 폐쇄되지 않은 의한되고 사용되었는지 확인하는 방법 예외를 throw ? 당신의 StreamWriter이 범위를 벗어나 선언하기 때문이다

+1

에 또한 using 문을 사용 하는가? 처음에는? – Steve

+1

프로그램이이 함수에 처음으로 액세스하거나 전체 프로세스 (빌드, 보내기)가 동일한 파일 이름으로 두 번 이상 반복됩니다. – Steve

+0

두 번째로 프로그래머가이 함수를 처리 할 때 발생합니다 – user609511

답변

1

그것을 잠금 무엇.
어느 경우 든 MailMessage 클래스의 MailMsg.Dispose()으로 전화해야합니다. 그렇지 않으면 다음 번에 파일에 기록하려고 할 때 파일이 잠기 게됩니다.

보십시오 당신이있는 당신은 예외 선에서 더 구체적인 될 수있는은 MailMessage

 try 
     { 
      Pers_Conf oConf = LeConf.Get_Config(CodeClient); 

      using(MailMessage omail = new MailMessage()) 
      { 
       ..... 
       oSmtp.Send(omail); 
      } 
     } 
     catch (Exception excThrown) 
     { 
      throw excThrown; 
     } 
+0

고맙습니다 ... 저의 문제를 해결하십시오. – user609511

0

, 대신이 시도 :

using (StreamWriter sw = new StreamWriter(strFilePath, false)) 
{ 
} 

이 컴파일 시간에 당신을 위해 tryfinally 코드를 추가합니다. 당신이 try 블록을 지정하려는 경우 또는, 자신이 작업을 수행 :

StreamWriter sw; 

try 
{ 
    sw = new StreamWriter(strFilePath, false); 
} 
catch 
{ 
} 
finally 
{ 
    sw.Flush(); 
    sw.Close(); 
    sw.Dispose();   
} 

이것은 finally에 그것을 범위를 제공 할 것입니다.

편집

당신은 당신의 파일을 만들려면 파일 스트림에 using 블록을 추가하려고하고, 대린가 지적한대로 일을 이미 가지있는 한 후 StreamWriter으로이 스트림에 쓸 수 있습니다.

using (FileStream fs = new FileStream(strFilePath, FileMode.Create, FileAccess.Write)) 
{ 
    using (StreamWriter sw = new StreamWriter(fs)) 
    { 
     // write your content 

     sw.Flush(); 
     sw.Close(); 
    } 

    fs.Close(); 
} 

당신이 코드에서 보이는 (하지만이 설명으로)로 다음 당신은 당신의 FileStream 그래서이 요인이 될 수 있습니다 폐쇄하지 않을 File.Create을 사용하여 파일을 만드는 경우.

+2

현재 그가 갖고있는 것입니다. 'CreateCSVFile' 메쏘드 안에서 그의 코드를 다시 한번보십시오. –

+0

@DarinDimitrov : 그래, 그건 약간의 게으른 독서였습니다. 나는 마지막 질문에 그 질문이 있다고 생각했을뿐입니다. –

0

StreamWriter가 범위를 벗어납니다. 당신이 코드 sw의 마지막 블록에서 ... 다음에

StreamWriter sw; 
try 
{ 
    sw = new StreamWriter(strFilePath, false); 
} 
Catch 
{ 

} 
finally 
{ 
sw.Flush(); 
sw.Close(); 
sw.Dispose(); 
} 
0

을 굴절 경우이 범위를 벗어나 있기 때문에 인식되지 않습니다.

이 시도하십시오 : 첫 번째 attemopt 합리적인처럼

using (StreamWriter sw = new StreamWriter(strFilePath, false)) 
{ 
    // Just do your thing, at the end sw will be cleaned up for you :) 
} 
0

그래서, 그것은 (아래 요약에) 보이는

using (var sw = new StreamWriter(strFilePath, false)) 
{ 
    sw.Flush(); 
    sw.Close(); 
    sw.Dispose(); 
} 
:

StreamWriter sw; 

try 
{ 
    sw = new StreamWriter(strFilePath, false); 
} 
catch 
{ 
    // Never do an empty catch BTW!  
} 
finally 
{ 
    if (sw != null) 
    { 
    sw.Flush(); 
    sw.Close(); 
    sw.Dispose(); 
    } 
} 

또는 더 나은 아직이하는 using 문을 사용

sw..Dispose()는 {} 블록을 사용하고 있기 때문에 필요하지 않습니다.

그래서 당신이보고 있던 문제가 정확히 무엇입니까?

좋아, 편집을 보았습니다. 파일을 잠그고있는 다른 파일이 아니라고 확신합니까? 아마도 첨부 파일 일 수 있습니다. 이 범위가 선언 된 범위를 볼 수 없지만 파일에 매달려있을 가능성이 있습니까? 검사 할 경우 한 번 더이 코드를 입력 가정하면 ... 당신은 ProcessMonitor을 사용할 수 있습니다

http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx

관련 문제