2011-07-18 5 views
1

나는 메타 데이터 (FIDEF)와 해당 비디오 파일이있는 파일을 가져와 XSLT를 사용하여 XML (FIDEF)을 변환하는 Windows 서비스를 가지고 있습니다.C# 서비스 이름 바꾸기 파일!

FIDEF의 파일 디렉토리 목록을 얻었고 같은 이름의 비디오 파일이 있으면 변환합니다. 그래도 작동하지만 매분마다 검색하는 타이머가 있습니다. 같은 파일 이름이 입력 디렉토리에 있지만 이미 출력 디렉토리에있는 상황을 처리하려고합니다. 나는 단지 출력 이름을 (복사)로 바꿔서 다른 파일이 들어가면 (복사) (복사) .mov를 가져야하지만 서비스는 이미 출력에있는 같은 디렉토리의 파일 이름으로 시작하지 않을 것이다. 다음 새 파일을 선택하지 않는 것 같습니다.

아무런 도움이되지 않아 몇 가지 시도를 해본 결과 도움이 될 것입니다. 나는 그것의 이름 바꾸기 방법을 믿는다, 그러나 나는 그것의 정리 문제 또는 다른 것을 위해 대부분의 코드를 넣었다. (다른 이름을 사용하려는 일부 이름은 용서하십시오.)

private void getFileList() 
    { 
     //Get FILE LIST FROM Directory 
     try 
     { 
      // Process Each String/File In Directory 
      string result; 
      //string filename; 
      filepaths = null; 
      filepaths = Directory.GetFiles(path, Filetype); 

      foreach (string s in filepaths) 
      { 

       for (int i = 0; i < filepaths.Length; i++) 
       { 
        //Result Returns Video Name 
        result = Path.GetFileNameWithoutExtension(filepaths[i]); 
        FileInfo f = new FileInfo(filepaths[i]); 

        PreformTranslation(f, outputPath + result , result); 


       } 
      } 

     } 
     catch (Exception e) 
     { 
      EventLog.WriteEntry("Error " + e); 
     } 


    } 

    private void MoveVideoFiles(String Input, String Output) 
    { 
     File.Move(Input, Output); 

    } 
    private string GetUniqueName(string name) 
    { 


     //Original Filename 
     String ValidName = name; 
     //remove FIDEF from filename 
     String Justname1 = Path.GetFileNameWithoutExtension(name); 
     //get .mov extension 
     String Extension2 = Path.GetExtension(Justname1); 
     //get filename with NO extensions 
     String Justname = Path.GetFileNameWithoutExtension(Justname1); 
     //get .Fidef 
     String Extension = Path.GetExtension(name); 
     int cnt = 0; 

     //string[] FileName = Justname.Split('('); 
     //string Name = FileName[0]; 

     while (File.Exists(ValidName)==true) 
     { 
      ValidName = outputPath + Justname + "(Copy)" + Extension2 + Extension; 
      cnt++; 

     } 
     return ValidName; 
    } 
    private string getMovFile(string name) 
    { 
     String ValidName = name; 
     String Ext = Path.GetExtension(name); 
     String JustName = Path.GetFileNameWithoutExtension(name); 

     while(File.Exists(ValidName)) 
     { 
      ValidName = outputPath + JustName + "(Copy)" + Ext; 
     } 
     return ValidName; 
    } 



    //Preforms the translation requires XSL & FIDEF name. 
    private void PreformTranslation(FileInfo FileName, String OutputFileName , String result) 
    { 

     string FidefName = OutputFileName + ".FIDEF"; 
     String CopyName; 
     String copyVidName = outputPath + result; 

      XslCompiledTransform myXslTransform; 
      myXslTransform = new XslCompiledTransform(); 
      try 
      { 
       myXslTransform.Load(XSLname); 

      } 
      catch 
      { 
       EventLog.WriteEntry("Error in loading XSL"); 
      } 
      try 
      { //only process FIDEF's with corresponding Video file 
       if (AllFidef == "no") 
       { 
        //Check if video exists if yes, 
        if (File.Exists(path + result)) 
        { 
         //Check for FIDEF File Already Existing in the Output Directory. 
         if (File.Exists(FidefName)) 
         { 
          //Get unique name 
          CopyName = GetUniqueName(FidefName); 
          copyVidName= getMovFile(copyVidName); 


          //Translate and create new FIDEF. 

          //double checking the file is here 
          if (File.Exists(outputPath + result)) 
          { 
           myXslTransform.Transform(FileName.ToString(), CopyName); 
           File.Delete(FileName.ToString()); 
           MoveVideoFiles(path + result, copyVidName); 

          } 
          ////Move Video file with Corresponding Name. 

         } 


         else 
         { //If no duplicate file exsists in Directory just move. 
          myXslTransform.Transform(FileName.ToString(), OutputFileName + ".FIDEF"); 
          MoveVideoFiles(path + result, outputPath + result); 
         } 
        } 

        } 
       else 
       { 
        //Must have FIDEF extension 
        //Processes All FIDEFS and moves any video files if found. 
        myXslTransform.Transform(FileName.ToString(), OutputFileName + ".FIDEF"); 
        if (File.Exists(path + result)) 
        { 
         MoveVideoFiles(path + result, outputPath + result); 
        } 


       } 
      } 
      catch (Exception e) 
      { 
       EventLog.WriteEntry("Error Transforming " + "FILENAME = " + FileName.ToString() 
        + " OUTPUT_FILENAME = " + OutputFileName + "\r\n" +"\r\n"+ e); 

      } 

     } 
+0

내부 'for' 루프가있는 이유는 무엇입니까? 그것은 기본적으로'foreach'를 복제합니다. –

답변

1

코드에 많은 문제가 있습니다. getFileList에는 시작을위한 불필요한 내부 루프 for이 있습니다. 그것을 제거. foreach 루프의 범위는 s이며 for 루프의 filepaths[i]을 대체 할 수 있습니다. 또한 파일 경로를 만들 때는 outputPath + result을 사용하지 마십시오. Path.Combine은 디렉토리 문자를 처리하기 때문에 Path.Combine(outputPath, result)을 대신 사용하십시오. 또한 getFileList의 더 나은 이름을 제안해야합니다. 그 방법은 전혀 작동하지 않기 때문입니다. 당신의 방법 이름 거짓말을하지 마십시오.

나는 간단하게 MoveVideoFiles을 제거합니다. 컴파일러도 마찬가지 일 수 있습니다.

GetUniqueName은 파일 이름이 name.mov.fidef 인 경우에만 작동합니다. 이는 가정합니다. 그래도 변수 이름이 더 필요합니다. 그렇지 않으면 나중에 유지 보수 용 nightware가됩니다. 루프 상태 인 while에서 == true을 없애 겠지만 선택 사항입니다. while 안에있는 과제는 파일을 덮어 쓰는 이유입니다. 당신은 항상 동일한 이름 (something(Copy).mov.fidef)을 생성하고, 내가 볼 수있는 한, 파일이 존재한다면, 당신은 스택을 영원히 돌리는 것을 생각해 봅니다. 이 루프를 수정하여 새 이름을 생성해야합니다 (잊지 말고 Path.Combine). 그래서

int copyCount = 0; 
while (File.Exists(ValidName)) 
{ 
    const string CopyName = "(Copy)"; 
    string copyString = copyCount == 0 ? CopyName : (CopyName + "(" + copyCount + ")"); 
    string tempName = Justname + copyString + Extension2 + Extension; 
    ValidName = Path.Combine(outputPath, tempName); 
    copyCount++; 
} 

이 두 번째의 첫 번째 복사본에 대한 something(Copy).mov.fidef, something(Copy)(2).mov.fidef를 생성하고 : 어쩌면이 같은 (이 안된 참고). 어쩌면 당신이 원하는 것이 아닌, 조정할 수 있습니다.

이 시점에서해야 할 일이 많습니다. getMovFile은 마치 GetUniqueName과 같은 방식으로 작업을 사용할 수있는 것처럼 보입니다. 너는 그것을 알아낼 것이다. 행운을 빕니다.

+0

그래 코드가 잘 작동합니다! (tempString에 copyString이 추가되었습니다.) 변경 및 팁에 대한 도움을 주셔서 감사합니다. 정말 큰 도움은 나쁜 습관을 배우지 말아야한다는 것입니다. :) – user685590

+0

우수. 기꺼이 도와주세요. –