Saturday 15 March 2014

c# 4.0 - Access to the path is denied - C# -



c# 4.0 - Access to the path is denied - C# -

i have written programme copies files. sometimes, while trying re-create file exception thrown - "access path ... denied". (probably because programme uses file).

notice: run programme administrator

but! when re-create same file manually works!

why? wrong program?

try { copyclass.copy(m_filessources[i].path, m_filesdestinations[i], true, m_filessources[i].postfix); } grab (exception ex) { isaccessdenied = true; tblog.text += " - " + ex.message + "\n"; } class copyclass { public static bool copy(string sourcedirpath, string destdirpath, bool copysubdirs, string postfix) { if (postfix == null) { filecopy(sourcedirpath, destdirpath, copysubdirs); homecoming true; } directorycopy(sourcedirpath, destdirpath, copysubdirs, postfix); homecoming true; } public static void directorycopy(string sourcedirname, string destdirname, bool copysubdirs, string postfix) { // subdirectories specified directory. directoryinfo dir = new directoryinfo(sourcedirname); directoryinfo[] dirs = dir.getdirectories(); // if destination directory doesn't exist, create it. if (!directory.exists(destdirname)) { directory.createdirectory(destdirname); } // files in directory , re-create them new location. fileinfo[] files = dir.getfiles(); foreach (fileinfo file in files) { string temppath = system.io.path.combine(destdirname, file.name); if (postfix == ".") { file.copyto(temppath, copysubdirs); } else if (file.name.endswith(postfix)) { file.copyto(temppath, copysubdirs); } } // if copying subdirectories, re-create them , contents new location. if (copysubdirs) { foreach (directoryinfo subdir in dirs) { string temppath = system.io.path.combine(destdirname, subdir.name); directorycopy(subdir.fullname, temppath, copysubdirs, postfix); } } } public static void filecopy(string sourcefilename, string destdirname, bool overwrite) { string destfilename = destdirname + sourcefilename.substring(sourcefilename.lastindexof('\\') + 1); // if destination directory doesn't exist, create it. if (!directory.exists(destdirname)) { directory.createdirectory(destdirname); } system.io.file.copy(sourcefilename, destfilename, overwrite); } }

}

the problem file had tried overwrite read-only. solve problem i've manually changed attributes of destination file normal (not read-only):

if (file.exists(destfilename)) { file.setattributes(destfilename, fileattributes.normal); // makes every read-only file rw file (in order prevent "access denied" error) }

hope helpful.

c#-4.0

No comments:

Post a Comment