Ahmad Raza
Ahmad Raza

Reputation: 1929

Move a File from a source to a destination in C#

I want to move a file abc.text from D drive to data folder in E drive using

System.IO.File.Move("D:\\abc.text", "E:\\data");

but it throws exception "Access to destination is denied" and there is not any Lock on my E drive which can cause access deny. How i can avoid from this exception?

Upvotes: 0

Views: 468

Answers (2)

Fᴀʀʜᴀɴ Aɴᴀᴍ
Fᴀʀʜᴀɴ Aɴᴀᴍ

Reputation: 6251

You need to specify the full name of the file:

System.IO.File.Move("D:\\abc.text", "E:\\data\\abc.text");

However you should have got this exception instead:

An exception of type 'System.IO.DirectoryNotFoundException' occurred in mscorlib.dll but was not handled in user code

So, make sure that you have access to the data folder of your E:\ drive. Check the properties of that folder, make sure it is not 'Read-Only`.

One reason why you might be getting that exception is that there exists a file named data in the drive already, it maybe hidden/protected. And side-by-side you have a folder named data. Provided you specify the file name as well, i.e. the full path of the destination file, your problem should be resolved.

Upvotes: 3

Mikes3ds
Mikes3ds

Reputation: 600

Run as administrative mode. You can do this by right clicking on visual studio when starting it.

(Note tested your code it works fine, probably you just need to be ruining as admin to move the file. System.IO.File.Move("D:\abc.text", "E:\data\abc.text");)

Upvotes: 1

Related Questions