How to select an internal file randomly from a folder and then save it? C # [closed]

-1

Hi, I'm here I'm a new user in Stack, I've arrived here because of this questionnaire I have, I'm doing a project in C # Personal in regard to this program I want to randomly select a file from an internal folder of the project (Any type of file such as zip, rar or PSD), keep it and then save it in another directory.

  • I'm using Forms.

Greetings:)

    
asked by Tomas Segundo Lastarria 10.09.2018 в 16:51
source

2 answers

2

To select random files you could use something like

 //obtienes la lista de archivos de la carpeta
 string[] files = Directory.GetFiles("<ruta origen>", "*.*");

 int index = Random.Next(0, files.Length);

 string file = files[index];

 File.Copy(file, "<aqui path destino>");

some doc about these methods

Random.Next (Int32, Int32)

Directory.GetFiles (String, String)

    
answered by 11.09.2018 в 15:53
2

It's not very difficult to do what you want here, I'll add my solution, I'll explain.

The first thing you should do is define your origen and destino routes within the project. When you have defined your routes, you get the directory information where is the path of destino to that directory, you ask for the files it contains and it will return a > arrangement with everything.

To that arrangement you will apply a random with the amount of files that contains the directory , when you have the selected file define your routes of origen and destino to copy only that file. In case you do not have the folder created, it will be created automatically with a condition.

try
{
    //DEFINIR LAS RUTAS DE ORIGEN Y DESTINO
    string source = Path.GetFullPath(Path.Combine(Application.StartupPath, @"..\..\Carpeta"));
    string target = Path.GetFullPath(Path.Combine(Application.StartupPath, @"..\..\Carpeta2"));
    //OBTENER LA INFORMACIÓN DEL DIRECTORIO DONDE SE ENCUENTRAN LOS ARCHIVOS
    DirectoryInfo directory = new DirectoryInfo(source);
    FileInfo[] files = directory.GetFiles();
    //APLICAR METODO ALEATORIO PARA SELECCIONAR LOS ARCHIVOS DEL ARREGLO
    Random rand = new Random();
    FileInfo file = files[rand.Next(files.Count())];
    //DEFINIR LAS RUTAS DE ORIGEN Y DESTINO CON EL ARCHIVO SELECCIONADO
    string fileName = file.Name;
    string sourceFile = Path.Combine(source, fileName);
    string destFile = Path.Combine(target, fileName);
    //CREAR DIRECTORIO SI NO EXISTE
    if (!Directory.Exists(target))
        Directory.CreateDirectory(target);
    //COPIAR EL ARCHIVO A LA RUTA DESTINO INDICADA CON SU RESPECTIVO ARCHIVO
    File.Copy(sourceFile, destFile, true);
    MessageBox.Show("Se ha copiado correctamente el archivo.");
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message);
}
    
answered by 11.09.2018 в 16:26