Error on delete file at Windows Mobile 6.5 - c#

I'm working on a project for windows mobile 6.5. I am using C # with compact framework 3.5 (CF 3.5) and SDK for Windows Mobile 6.5.
My routine writes files to a temporary directory for further processing. After a few days the file is renamed and directed to a purge.
When trying to delete the file the following error occurs: Access to the path '\Application Data\Volatile\Temp\20170822-97703.Nf.env' is denied.
Where:
\Application Data\Volatile is the default temporary directory Path.GetTempPath()
\Temp is my temporary directory
20170822-97703.Nf.env is my file.
Code:
const string dirTemp= "Temp";
public void PurgeFiles()
{
DateTime datePurge= new DateTime();
datePurge= DateTime.Now.AddDays(-7);
var files= FindFiles();
foreach (string file in files)
{
var dateAlt = Directory.GetLastWriteTime(file);
if (dateAlt< datePurge)
{
Directory.Delete(file);
}
}
}
private string[] FindFiles()
{
string searchPattern;
string dirLocal;
dirLocal= Path.GetTempPath();
dirLocal= Path.Combine(dirLocal, dirTemp);
if (Directory.Exists(dirLocal))
{
searchPattern = "*.Env";
var files = Directory.GetFiles(dirLocal, searchPattern);
return files;
}
else
return new string[0];
}
Save file
public bool SaveFile(string dir, string fileName, string content)
{
try
{
if (!Directory.Exists(dir))
Directory.CreateDirectory(dir);
string pathFile = Path.Combine(dir, fileName);
if (File.Exists(pathFile))
return true;
//Salva os dados
StreamWriter fileConf = new StreamWriter(pathFile);
fileConf.Write(content);
fileConf.Flush();
fileConf.Close();
return true;
}
catch (Exception ex)
{
return false;
}
}
Mark the file as processed
public void MarkFile(string fileName)
{
try
{
string newFileName= fileName + ".env";
if (File.Exists(newFileName))
return;
File.Move(fileName , newFileName);
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}

To can delete the file I changed the name of file and the line below
Directory.Delete(file);
for
File.Delete(file);

Related

How can I run an exe file with c# (I can't use Process.Start() because I don't know the exe file's location)

I want to run an exe file with c# but I can't use Process.Start() because I don't know the exe file's location.
I didn't start to writing so I don't have any code for now.
Use following :
string locateFile = "cmd.exe";
string environPath = Environment.GetEnvironmentVariable("Path");
string[] paths = environPath.Split(new char[] { ';' }).ToArray();
string filePath = "";
foreach (string path in paths)
{
string file = Directory.GetFiles(path, locateFile, SearchOption.TopDirectoryOnly).FirstOrDefault();
if (file != null)
{
filePath = file;
break;
}
}
if (filePath.Length > 0)
{
Console.WriteLine("File location : '{0}'", filePath);
}
else
{
Console.WriteLine("File not found");
}
Console.ReadLine();

Getting full path of file by name of file it gives access denied

I have a situation where the user will enter the name of the file and at run-time (without specifying the path). And i must find out the file by c# code.
I have seen a function GetFullPath() but it just give the current directory path appended by fileName entered by user at run-time.
string fullPath;
Console.WriteLine("please enter teh name of the file to be searched");
String fileName = Console.ReadLine();
fullPath = Path.GetFullPath(fileName);
Is there any such way exist in c# to get full path of a file specified at run time ? (Without specifying about the path). I can convince the user for specifying the Drive (C:/D:/E:...) but for writing the full path at run time to find that file they will not agree.
EDIT: My try is this: (but it gives access denied) please help me if i am not smart enough to go to each directory and do not try to open the secured folder until i get my file.
public static string Search(string fileName)
{
string fullPath = string.Empty;
WindowsIdentity currentIdentity = WindowsIdentity.GetCurrent();
WindowsPrincipal currentPrincipal = new WindowsPrincipal(currentIdentity);
if (currentPrincipal.IsInRole(WindowsBuiltInRole.Administrator))
{
try
{
foreach (string fpath in Directory.GetFiles("F:\\", "*", SearchOption.AllDirectories))
{
try
{
if (fpath.Substring(fpath.LastIndexOf("\\") + 1).ToUpper().Contains(fileName.ToUpper()))
fullPath = fpath;
}
catch (UnauthorizedAccessException)
{
Console.WriteLine("Access denied to folder1: " + fullPath);
}
}
}
catch (UnauthorizedAccessException)
{
Console.WriteLine("Access denied to folder2: " + fullPath);
}
}
else
{
Console.WriteLine("You are not authorized");
}
return fullPath;
}
If you're searching for a file you can use the following to search all directories. Assuming the user inputs the entire filename (including the extension) and a source drive/location.
string fullPath = string.Empty;
Console.WriteLine("please enter the name of the file to be searched");
String fileName = Console.ReadLine();
foreach(string fpath in Directory.GetFiles("C:\\", "*", SearchOption.AllDirectories))
{
if (fpath.Substring(fpath.LastIndexOf("\\") + 1).ToUpper() == fileName.ToUpper())
fullpath = fpath;
}
Alternatively, if the user inputs part of the file (excluding extention) use..
foreach(string fpath in Directory.GetFiles("C:\\", "*", SearchOption.AllDirectories))
{
if (fpath.Substring(fpath.LastIndexOf("\\") + 1).ToUpper().Contains(fileName.ToUpper()))
fullpath = fpath;
}
Add to an array or list incase multiple results (paths) are found.
Like so..
var foundPaths = Directory.GetFiles("C:\\", "*", SearchOption.AllDirectories)
.Where(x => x.ToUpper().Contains(fileName.ToUpper()))
.Select(x => x)
.ToList();
I found solution my self, I am doing recursive call until i don't get file to be searched:
List<string> directories = new List<string>(Directory.GetDirectories(driveName));
string name=null;
foreach(string directry in directories)
{
if (GetFileInformation(directry, out name))
{
try
{
DirSearch(directry, fileName, ref foundVar);
}
catch (System.Exception excpt)
{
Console.WriteLine("from except msg :" + excpt.Message);
if(foundVar==true)
{
break;
}
}
}
}
And then the function definition is :
public static void DirSearch(string sDir, string fileName, ref bool foundVar)
{
try
{
foreach (string d in Directory.GetDirectories(sDir))
{
foreach (string f in Directory.GetFiles(d, fileName))
{
if (Path.GetFileName(f) == fileName)
{
Console.WriteLine("directory is and inside it is " + f);
OpenExeFile(f);
foundVar = true;
break;
}
}
DirSearch(d, fileName, ref foundVar);
}
}
catch (System.Exception excpt)
{
Console.WriteLine(excpt.Message);
}
}

Delete a folder whose items are open in browser

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)
{
}
}

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");

Error while handling multiple txt files

I'm constructing a program to search all .xml inside a folder setted by user (Source folder) and copy all these files to another folder (Destination folder).
My program is able to search all XML within all sub folders from (Source folder), the result returns around 5000 files that are placed on a list, this list is worked later by a function, but he can only work with 31 files, then appears "not responding "and the debugger shows that the program is staying a long time in the execution.
Here is my code:
Button action:
private void btnCopiarSalvar_Click(object sender, EventArgs e)
{
foreach (string name in listFileNames)
{
if (readXML(name ))
{
tbArquivo.Text = name ; //Feedback textbox, tell the current filename
}
}
pbStatus.Increment(50);
cbFinal.Checked = true; //Feedback checkBox, to tell user that the task is over.
}
Function ReadXML
public bool readXML(string name)
{
//foreach (string nome in listaArquivos)
//{ //I tried to the foreach inside, but nothing Works.
try
{
string text = null;
string readBuffer = File.ReadAllText(name);
text = readBuffer.Aggregate(text, (current, b) => current + b);
var encoding = new ASCIIEncoding();
Byte[] textobytes = encoding.GetBytes(text);
if (!File.Exists(destino))
{
string destinoComNomeArquivo = destino + "\\" + Path.GetFileName(nome);
using (FileStream fs = File.Create(destinoComNomeArquivo))
{
foreach (byte textobyte in textobytes)
{
fs.WriteByte(textobyte);
pbProcess.PerformStep();
}
Console.WriteLine("Arquivo gravado " + Path.GetFileName(nome));
}
}
pbProcess.PerformStep();
}
catch (Exception e)
{
Console.WriteLine(e);
}
//}
return true;
}
Error: ContextSwitchDeadlock was detected.
Tried Solution: Disable Managed Debug Assistants.
After disabling the MDA, the programs still only read-copy 31 files (of 5k).
The first thing i recommand is ... don't do that kind of file copy! use the File.Copy function instead.
Try to use this code snipping from MSDN:
void DoCopy(string path)
{
var copytask = new Task(() =>
{
string destinoComNomeArquivo = #"C:\" + Path.GetFileName(path);
DirectoryCopy(path, destinoComNomeArquivo, false);
});
copytask.Start();
}
private void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs)
{
DirectoryInfo dir = new DirectoryInfo(sourceDirName);
DirectoryInfo[] dirs = dir.GetDirectories();
if (!dir.Exists)
{
throw new DirectoryNotFoundException(
"Source directory does not exist or could not be found: "
+ sourceDirName);
}
if (!Directory.Exists(destDirName))
{
Directory.CreateDirectory(destDirName);
}
FileInfo[] files = dir.GetFiles();
foreach (FileInfo file in files)
{
string temppath = Path.Combine(destDirName, file.Name);
file.CopyTo(temppath, false);
}
var counter = 0;
var maxcounter = files.Count();
while (maxcounter < counter)
{
var item = files.ElementAt(counter).Name;
WriteAsnc(item);
counter++;
}
if (copySubDirs)
{
foreach (DirectoryInfo subdir in dirs)
{
string temppath = Path.Combine(destDirName, subdir.Name);
DirectoryCopy(subdir.FullName, temppath, copySubDirs);
}
}
}
const int _maxwritingprocess = Environment.ProcessorCount;
int _currentwritingtasks;
void WriteAsnc(string filepath)
{
_currentwritingtasks++;
var task = Task.Factory.StartNew(() =>
{
XDocument doc = XDocument.Load(filepath);
doc.Elements().First().Add(new XAttribute("Attribute Name","Attribute Value"));
doc.Save(filepath);
_currentwritingtasks--;
});
if(_currentwritingtasks == _maxwritingprocess)
task.Wait();
_currentwritingtasks--;
}
The next point the ContextSwitchDeadlock is a Threading problem and i thing your pbProcess is the source. What does that Process do i don't see anything of that process and i don't thing it is Impotent for your copy

Categories