2014-04-22 179 views
0
:20:S10734539/940 

正在讀取文件夾中的swift消息,並在行:20:我執行某種驗證以確定文件和讀取是否有效。在這種情況下,如果line:20:包含940,則windows服務在讀取完成後讀取並將其移至成功文件夾。但是一個無效的文件不會有940行:20:,windows服務是爲了將無效文件移動到無效的文件位置。我已經寫了一個代碼來做到這一點,但它無法移動文件。我收到一條錯誤消息'使用中的文件',查找我的代碼片段。將文件從文件夾移動到文件夾

if (Directory.Exists(@CBN_INFLOW940)) 
DirectoryInfo dr = new DirectoryInfo(CBN_INFLOW940); 
         FileInfo[] fi = dr.GetFiles(); 
         string[] files = Directory.GetFiles(CBN_INFLOW940); 

int lengthchk = 0;

if (files.Length < 1) 
    check = false; 

while (files.Length > lengthchk) 
{ 
    StringBuilder sb = new StringBuilder(); 
    logger.Info(fi[lengthchk].Name + ": read from folder"); 
    string narrationgen = ""; 
    bool isvalidrtgs = false; 
    DateTime createddate = fi[lengthchk].CreationTime.Date; 
    FileStream stream = null; 
    try 
    { 
    stream = File.Open(files[lengthchk], FileMode.Open, FileAccess.ReadWrite, FileShare.None); 
    StreamReader sf = new StreamReader(stream); 

    } 

if (line.Contains(":20:")) 
{ 
     firstchk = 1; 
     if (!line.Contains('/')) 
     { 
      string[] fnamesplit = fi[lengthchk].Name.Split('.'); 
      string newfname = fnamesplit[0] + "_bk" + ".txt"; 
      string destlocation = Invalidfilelocation940 + newfname; 
      string sourcelocation = CBN_INFLOW940 + fi[lengthchk]; // + "\\" 
      File.Move(sourcelocation, destlocation); 
      return; 
     } 
     string[] narr = line.Split('/'); 
     string filecode = narr[1]; 

     if (filecode.Trim() != "940") 
     { 
      string[] fnamesplit = fi[lengthchk].Name.Split('.'); 
      string newfname = fnamesplit[0] + "_bk" + ".txt"; 
      string destlocation = Invalidfilelocation940 + newfname; 
      string sourcelocation = CBN_INFLOW940 + "\\" + fi[lengthchk]; 
      File.Move(sourcelocation, destlocation); 

      return; 
     } 
} 
+0

在這裏發佈代碼時,*不要*使用製表符並嘗試限制縮進。這使得代碼更易於閱讀。 – crashmstr

+2

另外,您是否確定在嘗試移動之前關閉文件? – crashmstr

+0

嘗試從您的移動代碼中分離出您的支票代碼。這將是一個更好的設計,此外,當您嘗試移動文件時,您可能會鎖定文件進行閱讀。 – Derek

回答

0

嘗試從您的移動代碼分裂出來的校驗碼。這將是一個更好的設計,此外,當您嘗試移動文件時,您可能會鎖定文件進行閱讀。

想:

if (ShouldMoveFile(filename)) 
{ 
    File.Move... 
} 

並確保您關閉您正在閱讀的文件。

如果你保持代碼相同:

添加行:

sf.Close(); 
stream.Close(); 

你去移動文件之前。

1

問題可能是您打開了文件以進行讀取寫入。

stream = File.Open(files[lengthchk], FileMode.Open, FileAccess.ReadWrite, FileShare.None); 

這裏的文件訪問是殺手FileAccess.ReadWrite

可能,如果你打開它只是爲了閱讀你就可以移動,但實際上,當你閱讀完的文件,你應該關閉它在你嘗試移動它之前。

理想情況下,您可以使用一種方法檢查文件是否需要移動,另一種是執行移動。

+0

我將文件訪問權限改爲了讀取,但其仍然沒有移動。驗證後,webservice讀取文件,完成後移動到另一個位置,但是如果驗證爲false,則無法移動文件。 – user3560266

+0

然後您需要關閉該文件,然後再嘗試移動它。 –

相關問題