N
N
Nikita072019-04-09 11:03:21
.NET
Nikita07, 2019-04-09 11:03:21

How to move files according to a given condition?

Good afternoon, the essence of the question is as follows, there are several folders and files (for example, Documents and Service)
5cac503109143932421332.png
There is a C # code that should "scatter" files into folders (if the file is called "Document", then it must be placed in the "Documents" folder etc.)

using System;
using System.IO;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            string common_path = @"C:\Users\User\Documents\Test";
            string pathA = @"C:\Users\User\Documents\Test\Документы";
            string pathB = @"C:\Users\User\Documents\Test\Служебные";
            string[] files = Directory.GetFiles(common_path,"Д*");        // Получаем список всех файлов (Документов)
            foreach(string s in files)
            {
                File.Move(s, pathA);
            }
        }
    }
}

But when executed, the error "System.IO.IOException: Cannot create file because it already exists" occurs, but there is nothing in the package.
5cac516fe1803578212234.png
Why does this error occur?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexey Pavlov, 2019-04-09
@Nikita07

The second argument is not a folder, but the full path to a new file with a name.

var filename = Path.GetFileName(s);
File.Move(s, pathA + "\\" + filename);

J
Jan, 2019-04-09
@on1k

Before File.Move, first check if there is a file with the same name in the directory, if there is, then unique (at least add a number, at least a timestamp) name before moving the file.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question