How to check if the file name has 16 digits?

2
namespace _06_Teste
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void cmdValidar_Click(object sender, EventArgs e)
        {
            foreach (String file in Directory.GetFiles("c:\ImgRoute\Caixa9 D1\", "*.*"))
            {
                FileInfo fileName = new FileInfo(file);

                string imag = fileName.Name;

                if (imag.Length == 16)
                {
                    //("Numero do auto correto");
                }
                else
                {
                    //("Numero do auto invalido");
                }
            }
        }
    }
}
    
asked by anonymous 08.01.2015 / 14:00

2 answers

4

Add using at the beginning of the file:

using System.IO;

Example:

using System.IO;

namespace _06_Teste
{
    ......
    Directory.GetFiles(....)
    FileInfo fileName = new System.IO.FileInfo(file);

or call the functions using the full path

System.IO.Directory.GetFiles(....)
System.IO.FileInfo fileName = new System.IO.FileInfo(file);
    
08.01.2015 / 14:25
1

I believe you are trying to get the file name without extension, so you should use the GetFileNameWithoutExtension() ". I'll edit for more details.

foreach (var file in Directory.GetFiles("c:\ImgRoute\Caixa9 D1\", "*.*")) {
    var imag = Path.GetFileNameWithoutExtension(file);
    if (imag.Length == 16) {
        //("Numero do auto correto");
    } else {
        //("Numero do auto invalido");
    }
}

If you want with the extension you should use the GetFileName .

I'd rather use Directory.EnumerateFiles("c:\ImgRoute\Caixa9 D1\", "*.*") if you're using .Net 4 onwards. He is faster.

    
08.01.2015 / 14:28