Create folder on every console usage

Asked

Viewed 73 times

2

I took a program ready on the internet to create folder, so I tried to adapt it for me but I’m not getting.

I’d like every time I executed it, to create a subfolder inside the main under a different name, and that name be the day I was using it, hence if using 2x on the same day it would not erase the first folder just as if it were double ex 19/09... 19/09 (2).

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

public class CreateFileOrFolder
{
    static void Main()
    {
        // Specify a "currently active folder"
        string activeDir = @"B:\Quality\QAS\FOTOS DO FERRAMENTAL";

        //Create a new subfolder under the current active folder
        string newPath = System.IO.Path.Combine(activeDir, "19/09/2017");

        // Create the subfolder
        System.IO.Directory.CreateDirectory(newPath);

        // Create a new file name. This example generates
        // a random string.
        string newFileName = System.IO.Path.GetRandomFileName();

        // Combina o arquivo com o caminho
        newPath = System.IO.Path.Combine(newPath, newFileName);

        // Criar arquivo e sobrescrever ele.
        // DANGER: System.IO.File.Create will overwrite the file
        // Se já existe ele pode ocorrer a criação de arquivos random
        if (!System.IO.File.Exists(newPath))
        {
            using (System.IO.FileStream fs = System.IO.File.Create(newPath))
            {
                for (byte i = 0; i < 100; i++)
                {
                    fs.WriteByte(i);
                }
            }
        }

        // Ler a data de volta para provar 
        // se o código anterior funciona.
        try
        {
            byte[] readBuffer = System.IO.File.ReadAllBytes(newPath);
            foreach (byte b in readBuffer)
            {
                Console.WriteLine(b);
            }
        }
        catch (System.IO.IOException e)
        {
            Console.WriteLine(e.Message);
        }

        // manter o código aberto no debug.
        System.Console.WriteLine("Diretorio criado com sucesso, Pressione qualquer tecla para iniciar o programa de captura.");
        System.Console.ReadKey();
    }
}
  • And what is your doubt?

  • as I create several subfolders with different name, one not erasing the other

2 answers

2

Not to delete the folder and create a pasta(2), see this function:

void CriarPasta (string path)//Cria a função
{
    if (Directory.Exists(path)) //Verifica se já existe uma pasta com o mesmo nome
    {
        for (int i = 0; !Directory.Exists((path + "(" + i + ")")); i ++)//Verifica se exste uma pasta com o nome + (i)
        {
            Directory.CreateDirectory(path + "(" + i + ")");//Cria a pasta
        }
    }
    else // se não
      Directory.CreateDirectory(path);//Cria a pasta
}

1


If the name is the same it will not be created and will not erase anything, nothing will be done, nor will it make a mistake.

I improved a little, but this code is still bad.

using System;
using static System.Console;
using System.IO;

public class CreateFileOrFolder {
    public static void Main() {
        var activeDir = @"B:\Quality\QAS\FOTOS DO FERRAMENTAL";
        string newPath = Path.Combine(activeDir, DateTime.Now.ToString("yyyyMMdd"));
        Directory.CreateDirectory(newPath);
        newPath = Path.Combine(newPath, Path.GetRandomFileName());
        if (!File.Exists(newPath)) { //isto pode dar condição de corrida, mas vou deixar
            using (FileStream fs = File.Create(newPath)) {
                for (byte i = 0; i < 100; i++) {
                    fs.WriteByte(i); //isto é lento pra bedéu
                }
            }
        }
        byte[] readBuffer = File.ReadAllBytes(newPath);
        foreach (byte b in readBuffer) {
            WriteLine(b);
        }
        WriteLine("Diretorio criado com sucesso, Pressione qualquer tecla para iniciar o programa de captura.");
    }
}

See working in the Coding Ground. And in the .NET Fiddle. Also put on the Github for future reference.

  • Fighting Man, you helped me so much

Browser other questions tagged

You are not signed in. Login or sign up in order to post.