2016-05-25 3 views
1

У меня есть следующий фрагмент кода, который загружает файл и проверяет его достоверность. Первый выпуск:Предел символов в пути к файлу C#

if (RadUpload1.UploadedFiles.Count == 0) 
{ 
    Session[AppConstants.ERROR_MESSAGE] = ErrorsList.GetErrorMessage(
     ErrorsList.ERR_P_DATE_FILE_VALID); 
} 
else 
{ 
    if (RadUpload1.UploadedFiles.Count > 0) 
    { 
     foreach (UploadedFile validFile in RadUpload1.UploadedFiles) 
     { 
      FileInfo fi = new FileInfo(validFile.FileName); 
      Stream fs = validFile.InputStream; 

      IDbContextualRecord pFile = statusContext.CreateAndAddRecordForInsert(PartStoredFile.t_name); 
      pFile[PartStoredFile.c_partId] = _part[Part.c_id]; 
      string targetFolder = AppSession.Current.ConfigParameters[AppConstants.UPLOAD_FILE_PATH] + 
            "\\partRec\\" + _part[Part.c_id] + "\\" + pFile[PartStoredFile.c_id]; 

      long bytesOnTheStream = 0L; 
      try 
      { 
       DirectoryInfo dir = new DirectoryInfo(targetFolder); 
       if (dir.Exists == false) 
        dir.Create(); 

       string fullFileName = Path.Combine(targetFolder, fi.Name); 

       Stream targetStream = File.OpenWrite(fullFileName); 
       byte[] buffer = new Byte[AppConstants.BUFF_SIZE]; 
       int bytesRead; 

       // while the read method returns bytes 
       // keep writing them to the output stream 
       while ((bytesRead = fs.Read(buffer, 0, AppConstants.BUFF_SIZE)) > 0) 
       { 
        targetStream.Write(buffer, 0, bytesRead); 
        bytesOnTheStream += bytesRead; 
       } 

       fs.Close(); 
       targetStream.Close(); 
      } 
      catch (Exception ex) 
      { 
       throw ex; 
      } 

То, что я хочу сделать, это проверить, если количество символов в имени Filepath превышает 260 для отображения мне сообщение ошибки.

Это второй вопрос после того, как модификация была сделана:

if (RadUpload1.UploadedFiles.Count <= 0) 
{ 
    Session[AppConstants.ERROR_MESSAGE] = ErrorsList.GetErrorMessage(
            ErrorsList.ERR_P_DATE_FILE_VALID); 
} 
else 
{ 
    if (RadUpload1.UploadedFiles.Count > 0) 
    { 
     foreach (UploadedFile validFile in RadUpload1.UploadedFiles) 
     { 
      pomDoc = (IDbContextualRecord)Session[AppConstants.POM_DOCUMENT_NEW]; 

      FileInfo fi = new FileInfo(validFile.FileName); 
      Stream fs = validFile.InputStream; 

      IDbContextualRecord pomFile = pomContext.CreateAndAddRecordForInsert(PomFile.t_name); 
      pomFile[PomFile.c_pomDocumentId] = pomDoc[PomDocument.c_id]; 
      string targetFolder = AppSession.Current.ConfigParameters[AppConstants.UPLOAD_FILE_PATH] + "\\POM\\" + pomDoc[PomDocument.c_id] + "\\" + pomFile[PomFile.c_id]; 

      long bytesOnTheStream = 0L; 
      try 
      { 
       DirectoryInfo dir = new DirectoryInfo(targetFolder); 
       if (dir.Exists == false) 
        dir.Create(); 

       string fullFileName = Path.Combine(targetFolder, fi.Name); 

       if (fullFileName.Length > 260) 
       { 
        throw new Exception(string.Format("The filename is too long!",fullFileName)); 
       } 
       Stream targetStream = File.OpenWrite(fullFileName); 
       byte[] buffer = new Byte[AppConstants.BUFF_SIZE]; 
       int bytesRead; 

       // while the read method returns bytes 
       // keep writing them to the output stream 
       while ((bytesRead = fs.Read(buffer, 0, AppConstants.BUFF_SIZE)) > 0) 
       { 
        targetStream.Write(buffer, 0, bytesRead); 
        bytesOnTheStream += bytesRead; 
       } 

       fs.Close(); 
       targetStream.Close(); 
      } 
      catch (Exception ex) 
      { 
       throw ; 
      } 
+2

Так в чем проблема? fullFileName.Lenth - это не то, что вам нужно? – 3615

+0

правильный. Просто используйте функцию string.length. – DDave

+0

Должен ли я писать его после блоков try? Потому что ничего не делает. – Nomonom

ответ

1

Вы просто должны сравнить fullFileName.Lenght 260 и возбудит исключение, если это необходимо:

if (RadUpload1.UploadedFiles.Count <= 0) // Changed the condition to remove the check within the else block 
{ 
    Session[AppConstants.ERROR_MESSAGE] = ErrorsList.GetErrorMessage(
     ErrorsList.ERR_P_DATE_FILE_VALID); 
} 
else 
{ 
    foreach (UploadedFile validFile in RadUpload1.UploadedFiles) 
    { 
     FileInfo fi = new FileInfo(validFile.FileName); 
     Stream fs = validFile.InputStream; 

     IDbContextualRecord pFile = statusContext.CreateAndAddRecordForInsert(PartStoredFile.t_name); 
     pFile[PartStoredFile.c_partId] = _part[Part.c_id]; 
     string targetFolder = AppSession.Current.ConfigParameters[AppConstants.UPLOAD_FILE_PATH] + 
           "\\partRec\\" + _part[Part.c_id] + "\\" + pFile[PartStoredFile.c_id]; 

     long bytesOnTheStream = 0L; 
     try 
     { 
      DirectoryInfo dir = new DirectoryInfo(targetFolder); 
      if (dir.Exists == false) 
       dir.Create(); 

      string fullFileName = Path.Combine(targetFolder, fi.Name); 

      if(fullFileName.Length > 260) 
      { 
       throw new Exception(string.Format("The filename {0} is too long.", fullFileName)); 
       // Or do whatever you want 
      } 

      Stream targetStream = File.OpenWrite(fullFileName); 
      byte[] buffer = new Byte[AppConstants.BUFF_SIZE]; 
      int bytesRead; 

      // while the read method returns bytes 
      // keep writing them to the output stream 
      while ((bytesRead = fs.Read(buffer, 0, AppConstants.BUFF_SIZE)) > 0) 
      { 
       targetStream.Write(buffer, 0, bytesRead); 
       bytesOnTheStream += bytesRead; 
      } 

      fs.Close(); 
      targetStream.Close(); 
     } 
     catch (Exception ex) 
     { 
      throw; 
     } 

Кроме того, вы не хотите, чтобы throw ex;, а скорее throw;, или это сбросит стек, см. Is there a difference between "throw" and "throw ex"?

+0

необходимо бросить исключение: throw new Exception (string.Format ("Имя файла {0} слишком длинное.", FullFileName)); или он может отображать только сообщение? – Nomonom

+0

Ну, я написал, как раз за исключением * '// Или делаю то, что вы хотите * ... @Nomonom –

+0

Я спрашиваю, потому что у меня есть файлы с той же проблемой. В одном исключение отображается как сообщение, а в другом - исключение из кода. – Nomonom

Смежные вопросы