Delete a folder whose items are open in browser - c#

sdel = Server.MapPath("~/Media_Extracted_Content" + "/" + sfolder);
Directory.Delete(sdel,true);
'sfolder' contains different sub folder and all sub folder have contains different items. All items like image file, audio file, video file opened in browser .I am copying that items from this existing location to new location and after that I have to delete this directory from my system. Whenever I am trying to to this it shows error that Directory is not empty. Also, when I am trying to delete individual items from sub folder it is showing error that this file is being used by another process. Please help me.

I think at Server or at Hosting you have not given the permision to the folder which are, allow READ and WRITE to the Folder.

Please Try This Two FUNCTION/Method.
You only have to do is paste both function in class file(eg class1.cs).
In (aspx.cs)Assign Value to source and destination
For Example source = Server.MapPath("~/Media_Extracted_Content/" + sourcefolder);
destination = Server.MapPath("~/Media_Extracted_Content/" + destinationfolder);
And Call classobject.MoveFiles(source, destination,true);
public void createfolder(string directorypath)
{
// CREATE folder
try
{
Directory.CreateDirectory(directorypath);
}
catch (Exception ex)
{ }
}
public void MoveFiles(string source, string destination, bool overwrite)
{
System.IO.DirectoryInfo inputDir = new System.IO.DirectoryInfo(source);
System.IO.DirectoryInfo outputDir = new System.IO.DirectoryInfo(destination);
try
{
if ((inputDir.Exists))
{
if (!(outputDir.Exists))
{
createfolder(destination);
// outputDir.Create();
}
//Get Each files and copy
System.IO.FileInfo file = null;
foreach (System.IO.FileInfo eachfile in inputDir.GetFiles())
{
file = eachfile;
if ((overwrite))
{
file.CopyTo(System.IO.Path.Combine(outputDir.FullName, file.Name), true);
}
else
{
if (((System.IO.File.Exists(System.IO.Path.Combine(outputDir.FullName, file.Name))) == false))
{
file.CopyTo(System.IO.Path.Combine(outputDir.FullName, file.Name), false);
}
}
System.IO.File.Delete(file.FullName);
}
//Sub folder access code
System.IO.DirectoryInfo dir = null;
foreach (System.IO.DirectoryInfo subfolderFile in inputDir.GetDirectories())
{
dir = subfolderFile;
//Destination path
if ((dir.FullName != outputDir.ToString()))
{
MoveFiles(dir.FullName, System.IO.Path.Combine(outputDir.FullName, dir.Name), overwrite);
}
System.IO.Directory.Delete(dir.FullName);
}
}
}
catch (Exception ex)
{
}
}

Related

C# Copy file from Android to PC

I need to copy a bunch of files from an Android phone to the PC.
It doesn't work the normal way, the PC is super slow and crashes all the time for some reason.
I want to copy it file by file.
My problem is that if I use Directory.GetFiles("Path") or DirectoryInfo.GetFiles("Path") it does add the persistant Datapath to the path for some reason and I get this error message:
DirectoryNotFoundException: Could not find a part of the path 'D:\GameDev\CopyProgram\Dieser PC\HTC One M9\Interner gemeinsamer Speicher'.
The actual path is only "Dieser PC\HTC One M9\Interner gemeinsamer Speicher", is there any way to do that?
//there is an input field where you can enter the paths
(copy it from the explorer)
[SerializeField]
private string copyFrom = "Dieser PC\HTC One M9\Interner gemeinsamer Speicher";
[SerializeField]
private string copyTo = "C:\Users\Nutzer\Desktop\Neuer Ordner";
private bool running = false;
public void Copy()
{
if(running == true)
{
return;
}
running = true;
//Start
//Get all items from folder
DirectoryInfo d = new DirectoryInfo(copyFrom);
FileInfo[] Files = d.GetFiles();
foreach (FileInfo file in Files)
{
string currentFile = file.DirectoryName + "/" + file.Name;
string copyFile = copyTo + "/" + file.Name;
try
{
if (file == null)
continue;
File.Copy(currentFile, copyFile, true);
}
catch (Exception)
{
throw;
}
}
//End
running = false;
}
I searched through the internet and could not find a solution, please help!
Thanks!

FileNotFound Exception in gRPC C# 0.13.0 when used for webapplication

I updated my gPRC version for the WebApplication from 0.12.0 to 0.13.0 and it started failing to create a Channel object. Following is the exception thrown:
It is trying to locate grpc_csharp_ext.dll at AppData\\Local\\Temp\\Temporary ASP.NET Files\\root\\c8490d1a\\9f150f28\\assembly\\dl3\\5d08d985\\2c1c8757_6474d101\\nativelibs\\windows_x86\\grpc_csharp_ext.dll. I even stored the DLL in local bin folder but that didn't help. This problem does not occur if I create a Console app. I am not sure why it is trying to search the dll at the said location? Does anyone know how to make it work for a web application?
Edit This issue is fixed by GRPC Community as per Link. I have also verified the same. Now we need to keep the grpc_csharp_ext.dll under bin\nativelibs\windows_x86\ (for 32 bit dll) and bin\nativelibs\windows_x64\ (for 64 bit dll)
Asp.net performs Shadow Copying Assemblies during dynamic compilation. It copies Grpc.Core.dll but not the folder nativelibs that contains the native grpc_csharp_ext.dll files.
I have resolved this issue by programmatically coping the nativelibs folder.
Invoke the copy method from Application_Start in Global.asax.
public class WebApplication : HttpApplication
{
protected void Application_Start()
{
GrpcInitializer.EnsureGrpcCSharpExtNativeDll();
}
}
Copier:
public static class GrpcInitializer
{
public static void EnsureGrpcCSharpExtNativeDll()
{
var grpcCoreAssembly = Assembly.GetAssembly(typeof(Grpc.Core.Channel));
var srcFolderPath = Path.GetDirectoryName(new Uri(grpcCoreAssembly.CodeBase).LocalPath);
CopyGrpcCSharpExtNativeDll(srcFolderPath);
}
public static void CopyGrpcCSharpExtNativeDll(string srcFolderPath)
{
var grpcCoreAssembly = Assembly.GetAssembly(typeof(Grpc.Core.Channel));
var grpcDllLocation = Path.GetDirectoryName(grpcCoreAssembly.Location);
if (grpcDllLocation == null)
return;
var targetFolderPath = Path.Combine(grpcDllLocation, "nativelibs");
if (Directory.Exists(targetFolderPath))
return;
srcFolderPath = Path.Combine(srcFolderPath, "nativelibs");
DirectoryCopy(srcFolderPath, targetFolderPath, true);
}
private static void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs)
{
if (string.IsNullOrEmpty(sourceDirName) || string.IsNullOrEmpty(destDirName))
{
throw new ArgumentNullException(
$"Directory paths cannot be empty. sourceDirName: {sourceDirName} | destDirName: {destDirName}");
}
var dir = new DirectoryInfo(sourceDirName);
if (!dir.Exists)
{
throw new DirectoryNotFoundException("Source directory does not exist or could not be found: " +
sourceDirName);
}
var dirs = dir.GetDirectories();
if (!Directory.Exists(destDirName))
{
Directory.CreateDirectory(destDirName);
}
var files = dir.GetFiles();
foreach (var file in files)
{
string temppath = Path.Combine(destDirName, file.Name);
file.CopyTo(temppath, false);
}
if (copySubDirs)
{
foreach (var subdir in dirs)
{
var temppath = Path.Combine(destDirName, subdir.Name);
DirectoryCopy(subdir.FullName, temppath, true);
}
}
}
}

Deleting a specific folder and it's files ASP.NET

Alright so I'm having a bit of an issue here. I'm trying to delete a specific folder inside another folder on my webserver using ASP.NET (C#) The folder being deleted is based on a textbox.
The directory is like this
/images/folderx
folderx = txtDelFolder.Text;
The problem is that everything I try deletes every single thing inside the images folder. I'm guessing that it is not recognizing my folder in the filepath
string path = #"\httpdocs\images\ +
txtDelFolder.Text;
I have also tried
string path = #"\httpdocs\images\ +
txtDelFolder.Text + "\";
Tried all this with both single '\' and double '\'
Would appreciate any help on this
Also where it says <directfilepath> I actually have the filepath typed out, just didn't want to share that here.
****edit****
string path = Server.MapPath("~/imagestest/" + txtEditTitle.Text);
if(Directory.Exists(path))
{
DeleteDirectory(path);
}
}
}
private void DeleteDirectory(string path)
{
foreach(string filename in Directory.GetFiles(path))
{
File.Delete(filename);
}
foreach(string subfolders in Directory.GetDirectories(path))
{
Directory.Delete(subfolders, true);
}
}
Try this:
private void DeleteFiles(string folder)
{
string path=Server.MapPath("~/httpdocs/images/" + folder);
string[] files=Directory.GetFiles(path, "*", SearchOption.AllDirectories);
foreach (string file in files)
{
File.Delete(file);
}
//then delete folder
Directory.Delete(path);
}
try this one :
public void DeleteFolder(string folderPath)
{
if (!Directory.Exists(folderPath))
return;
// get the directory with the specific name
DirectoryInfo dir = new DirectoryInfo(folderPath);
try
{
foreach (FileInfo fi in dir.GetFiles())
fi.Delete();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Don't see why this wouldn't work:
public static bool DeleteDirectory(string input)
{
if (Directory.Exists(input))
{
Directory.Delete(input, true);
return !Directory.Exists(input);
}
else
return true;
}
string thePath = Server.MapPath(#"~/images/");
thePath = Path.Combine(Path.GetFullPath(thePath), txtInput.Text);
if(DeleteDirectory(thePath))
Console.WriteLine("YAY");
else
Console.WriteLine("BOO");

Directory.Move doesn't work (file already exist)

I've got main folder:
c:\test
And there I have 2 folders: Movies and Photos.
Photos has three folders with files with the same structure: People, Animals and Buildings. I'm trying this code:
Directory.Move(#"c:\test\Movies", #"c:\test\Test");
I get exception:
File already exists
This method will move content of a folder recursively and overwrite existing files.
You should add some exception handling.
Edit:
This method is implemented with a while loop and a stack instead of recursion.
public static void MoveDirectory(string source, string target)
{
var stack = new Stack<Folders>();
stack.Push(new Folders(source, target));
while (stack.Count > 0)
{
var folders = stack.Pop();
Directory.CreateDirectory(folders.Target);
foreach (var file in Directory.GetFiles(folders.Source, "*.*"))
{
string targetFile = Path.Combine(folders.Target, Path.GetFileName(file));
if (File.Exists(targetFile)) File.Delete(targetFile);
File.Move(file, targetFile);
}
foreach (var folder in Directory.GetDirectories(folders.Source))
{
stack.Push(new Folders(folder, Path.Combine(folders.Target, Path.GetFileName(folder))));
}
}
Directory.Delete(source, true);
}
public class Folders
{
public string Source { get; private set; }
public string Target { get; private set; }
public Folders(string source, string target)
{
Source = source;
Target = target;
}
}
Update:
This is a simpler version with the use of Directory.EnumerateFiles recursively instead of using a stack.
This will only work with .net 4 or later, to us it with an earlier version of .net change Directory.EnumerateFiles to Directory.GetFiles.
public static void MoveDirectory(string source, string target)
{
var sourcePath = source.TrimEnd('\\', ' ');
var targetPath = target.TrimEnd('\\', ' ');
var files = Directory.EnumerateFiles(sourcePath, "*", SearchOption.AllDirectories)
.GroupBy(s=> Path.GetDirectoryName(s));
foreach (var folder in files)
{
var targetFolder = folder.Key.Replace(sourcePath, targetPath);
Directory.CreateDirectory(targetFolder);
foreach (var file in folder)
{
var targetFile = Path.Combine(targetFolder, Path.GetFileName(file));
if (File.Exists(targetFile)) File.Delete(targetFile);
File.Move(file, targetFile);
}
}
Directory.Delete(source, true);
}
The destination directory should not already exist - the Directory.Move method creates the destination directory for you.
ProcessStartInfo p = new ProcessStartInfo("cmd", "/c move \"c:\\test\\Movies\" \"c:\\test\Test\\"");
p.WindowStyle = ProcessWindowStyle.Hidden; //hide mode
Process.Start(p);
Is it safe for you to delete the destination folder before copying new contents to it?
Directory.Delete(#"c:\test\test");
Directory.Move(#"c:\test\movies",#"c:\test\test");
The most common 2 reasons why Directory.Move could fail are, if:
It's a different volume (you need to Copy/Delete)
It already exists (doesn't support overwrite by default)
Here is my simple solution for the second problem (overwrite):
public bool MoveDirectory(string sourceDirName, string destDirName, bool overwrite)
{
if (overwrite && Directory.Exists(destDirName))
{
var needRestore = false;
var tmpDir = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
try
{
Directory.Move(destDirName, tmpDir);
needRestore = true; // only if fails
Directory.Move(sourceDirName, destDirName);
return true;
}
catch (Exception)
{
if (needRestore)
{
Directory.Move(tmpDir, destDirName);
}
}
finally
{
Directory.Delete(tmpDir, true);
}
}
else
{
Directory.Move(sourceDirName, destDirName); // Can throw an Exception
return true;
}
return false;
}
You can use move method directly.
Directory.Move(#"c:\test\Movies\", #"c:\test\Test\");
The folder will be deleted and copied it into Test Folder.

C# unload image from imagebox

I have a method whit the following logic:
I delete all files from input and output folders
user selects an initial picture
this pictures as being assigned to imageBox1
picture is being copied to the folder input
magic happens to picture and I put it to the folder output
new picture from output is beign assigned to imageBox2
Here is where problem starts. When users wants to repeat operation imagebox1 and imagebox2 do have pictures assigned to them. And the step #0 failswith error
The process cannot access the file '03933.tiff' because it is being used by another process.
What I was trying is :
private void CopyImage_Click(object sender, EventArgs e)
{
string currentPath = Directory.GetCurrentDirectory();
string pathInput = currentPath + "\\Input";
string pathOutput = currentPath + "\\Output";
if (pictureBoxInput.Image != null) {
pictureBoxInput.Image = null;
pictureBoxInput.Dispose();
}
if (pictureBoxOutput.Image != null) {
pictureBoxOutput.Image = null;
pictureBoxOutput.Dispose();
}
System.IO.DirectoryInfo di = new DirectoryInfo(pathInput + "\\");
foreach (FileInfo file in di.GetFiles())
{
file.Delete();
}
System.IO.DirectoryInfo dia = new DirectoryInfo(pathOutput + "\\");
foreach (FileInfo file in dia.GetFiles())
{
file.Delete();
}
But still having the same error when program tries to delete files.
I would suggest changing:
if (pictureBoxInput.Image != null) {
pictureBoxInput.Image = null;
pictureBoxInput.Dispose();
}
to:
if (pictureBoxInput.Image != null) {
var existingFile = pictureBoxInput.Image;
pictureBoxInput.Image = null;
existingFile?.Dispose();
}
and the same for pictureBoxOutput
The issue is that your existing code is disposing the wrong thing - you are disposing the PictureBox rather than the Image (and the Image is the thing that is holding the file lock).

Categories