Проблемы избавления от нескольких периодов в FileName - PullRequest
4 голосов
/ 20 июля 2010

Я пытаюсь взять имена файлов, которые выглядят так:MAX_1.01.01.03.pdf выглядит как Max_1010103.pdf.

В настоящее время у меня есть этот код:

public void Sanitizer(List<string> paths)
{
  string regPattern = (@"[~#&!%+{}]+");
  string replacement = " ";

  Regex regExPattern = new Regex(regPattern);
  Regex regExPattern2 = new Regex(@"\s{2,}");
  Regex regExPattern3 = new Regex(@"\.(?=.*\.)");
  string replace = "";

  var filesCount = new Dictionary<string, int>();
  dataGridView1.Rows.Clear();

  try
  {
    foreach (string files2 in paths)
    {
      string filenameOnly = System.IO.Path.GetFileName(files2);
      string pathOnly = System.IO.Path.GetDirectoryName(files2);
      string sanitizedFileName = regExPattern.Replace(filenameOnly, replacement);
      sanitizedFileName = regExPattern2.Replace(sanitizedFileName, replacement);
      string sanitized = System.IO.Path.Combine(pathOnly, sanitizedFileName);

      if (!System.IO.File.Exists(sanitized))
      {
        DataGridViewRow clean = new DataGridViewRow();
        clean.CreateCells(dataGridView1);
        clean.Cells[0].Value = pathOnly;
        clean.Cells[1].Value = filenameOnly;
        clean.Cells[2].Value = sanitizedFileName;

        dataGridView1.Rows.Add(clean);
        System.IO.File.Move(files2, sanitized);
      }
      else 
      {
        if (filesCount.ContainsKey(sanitized))
        {
          filesCount[sanitized]++;
        }
        else
        {
          filesCount.Add(sanitized, 1);
          string newFileName = String.Format("{0}{1}{2}",
              System.IO.Path.GetFileNameWithoutExtension(sanitized),
              filesCount[sanitized].ToString(),
              System.IO.Path.GetExtension(sanitized));

          string newFilePath = System.IO.Path.Combine(
              System.IO.Path.GetDirectoryName(sanitized), newFileName);
          newFileName = regExPattern2.Replace(newFileName, replacement);
          System.IO.File.Move(files2, newFilePath);
          sanitized = newFileName;

          DataGridViewRow clean = new DataGridViewRow();
          clean.CreateCells(dataGridView1);
          clean.Cells[0].Value = pathOnly;
          clean.Cells[1].Value = filenameOnly;
          clean.Cells[2].Value = newFileName;

          dataGridView1.Rows.Add(clean);
        }

//HERE IS WHERE I AM TRYING TO GET RID OF DOUBLE PERIODS//
        if (regExPattern3.IsMatch(files2))
        {
          string filewithDoublePName = System.IO.Path.GetFileName(files2);
          string doublepPath = System.IO.Path.GetDirectoryName(files2);
          string name = System.IO.Path.GetFileNameWithoutExtension(files2);
          string newName = name.Replace(".", "");
          string filesDir = System.IO.Path.GetDirectoryName(files2);
          string fileExt = System.IO.Path.GetExtension(files2);
          string newPath = System.IO.Path.Combine(filesDir, newName+fileExt);

          DataGridViewRow clean = new DataGridViewRow();
          clean.CreateCells(dataGridView1);
          clean.Cells[0].Value =doublepPath;
          clean.Cells[1].Value = filewithDoublePName;
          clean.Cells[2].Value = newName;
          dataGridView1.Rows.Add(clean);
        }
      }
    }
    catch (Exception e)
    {
      throw;
      //errors.Write(e);
    }
  }

Я запустил это и вместо того, чтобы избавиться от ВСЕХ периода (минус период перед расширением файла), я получаю результаты вроде: MAX_1.0103.pdf

Если есть несколько периодов, таких как: Test....1.txt Я получаю следующие результаты: Test...1.txt

Кажется, что избавляется только от ОДНОГО периода.Я довольно новичок в Регулярных выражениях, и это ТРЕБОВАНИЕ для этого проекта.Кто-нибудь может помочь мне выяснить, что я делаю здесь не так?

Спасибо!

РЕДАКТИРОВАНИЕ, чтобы показать изменения, внесенные в код

Ответы [ 5 ]

12 голосов
/ 20 июля 2010

Почему бы не использовать Path класс :

string name = Path.GetFileNameWithoutExtension(yourPath);
string newName = name.Replace(".", "");
string newPath = Path.Combine(Path.GetDirectoryName(yourPath),
                              newName + Path.GetExtension(yourPath));

Каждый шаг разделен для ясности.

Так что для ввода

"C: \ Users \ Fred \ MAX_1.01.01.03.pdf"

Я получаю вывод

"C: \ Users \ Fred \ MAX_1010103.pdf "

, что я и ожидал.

Если я поставлю:

" C: \ Users \ Fred.Flintstone \ MAX_1.01.01.03.pdf "

Я получаю:

" C: \ Users \ Fred.Flintstone \ MAX_1010103.pdf "

опять то, что я ожидаю, так как я не обрабатываю часть пути "DirectoryName".

NOTE Я пропустил бит о том, что RegEx - ТРЕБОВАНИЕ.Все еще придерживаюсь этого ответа, хотя.

2 голосов
/ 20 июля 2010

Скажите, разве вы не уже задавали этот вопрос ?

В любом случае, я придерживаюсь моего первоначального ответа :

string RemovePeriodsFromFilename(string fullPath)
{
    string dir = Path.GetDirectoryName(fullPath);
    string filename = Path.GetFileNameWithoutExtension(fullPath);
    string sanitized = filename.Replace(".", string.Empty);
    string ext = Path.GetExtension(fullPath);

    return Path.Combine(dir, sanitized + ext);
}

Теперь, так как вы указали, что вы должны использовать RegEx, я полагаю, вы всегда можете заставить это там:

string RemovePeriodsFromFilename(string fullPath)
{
    string dir = Path.GetDirectoryName(fullPath);
    string filename = Path.GetFileNameWithoutExtension(fullPath);

    // Look! Now the solution uses RegEx!
    string sanitized = Regex.Replace(filename, @"\.", string.Empty);

    string ext = Path.GetExtension(fullPath);

    return Path.Combine(dir, sanitized + ext);
}

Примечание: Это в основном то же самоеПодход, который ChrisF предложил.

Кто бы ни потребовал, чтобы вы использовали RegEx, я предлагаю вам запросить объяснение, почему.

0 голосов
/ 21 июля 2010

Это регулярное выражение удалит все периоды, кроме периода до расширения на 3 или 4 буквы.

string filename = "test.test......t.test.pdf";    
string newFilename = new Regex(@"\.(?!(\w{3,4}$))").Replace(filename, "");

Если вы хотите, чтобы он работал с двухбуквенными расширениями, просто измените {3,4} на {2,4}

Удачи!

0 голосов
/ 20 июля 2010

Я бы все вместе отказался от регулярных выражений, сделай это так:

  1. Заменить все периоды на пустые. струны
  2. Заменить последние 3 символы с ("." + последние 3 символы)
0 голосов
/ 20 июля 2010

Примерно так, может быть:

string fileName = "MAX_1.01.01.03.pdf";
fileName = fileName.Substring(0, 1).ToUpper() + fileName.Substring(1).ToLower();
fileName = fileName.Replace(".", "");
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...