I created a directory named "MyFolder" and wrote some text files there. Now, I want delete that directory and I am using the following code:
public void DeleteDirectory(string directoryName)
{
try
{
using (IsolatedStorageFile currentIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
if (!string.IsNullOrEmpty(directoryName) && currentIsolatedStorage.DirectoryExists(directoryName))
{
currentIsolatedStorage.DeleteDirectory(directoryName);
textBox1.Text = "deleted";
}
}
}
catch (Exception ex)
{
// do something with exception
}
}
I tried with
DeleteDirectory("MyFolder")
DeleteDirectory("IsolatedStore\\MyFolder")
however it didn't delete that directory. Any idea to solve that?
Have you deleted all of the contents of that directory?
http://msdn.microsoft.com/en-us/library/system.io.isolatedstorage.isolatedstoragefile.deletedirectory(v=vs.80).aspx
says (although it isn't the windows phone version of the documentation):
A directory must be empty before it is deleted. The deleted directory cannot be recovered once deleted.
The Deleting Files and Directories example demonstrates the use of the DeleteDirectory method.
Related
I am trying to locate a folder inside a Google Team Drive, which has a folder structure with multiple levels.
Here is an example:
Team Drive
- Folder A
- Folder B
- Folder C
I would like to search for Folder C by using the folder ID of the Team Drive. If the folder exists, return the folder ID for Folder C and if not, create that folder under Folder B.
So, I have some code I am working with, creating the Google Drive API query.
Here is the code snippet I am using - (Team Drive ID) would be the ID:
// Set the drive query...
String driveQuery = "mimeType='application/vnd.google-apps.folder' and '(Team Drive ID)' in parents and name='Folder C' and trashed=false";
try {
result = service.files().list().setQ(driveQuery).setIncludeTeamDriveItems(true).setSupportsTeamDrives(true)
.execute();
} catch (IOException e) {
e.printStackTrace();
}
for (File folder : result.getFiles()) {
System.out.printf("Found folder: %s (%s)\n", folder.getName(), folder.getId());
foundFolder = true;
folderID = folder.getId();
}
if (foundFolder != true) {
// Need to create the folder...
File fileMetadata = new File();
fileMetadata.setName(folderKeyToGet);
fileMetadata.setTeamDriveId(parentFolderID);
fileMetadata.set("supportsTeamDrives", true);
fileMetadata.setMimeType("application/vnd.google-apps.folder");
fileMetadata.setParents(Collections.singletonList(parentFolderID));
try {
newFolder = service.files().create(fileMetadata).setSupportsTeamDrives(true).setFields("id, parents")
.execute();
} catch (IOException e) {
e.printStackTrace();
}
// Send back the folder ID...
folderID = newFolder.getId();
System.out.println("Folder ID: " + newFolder.getId());
}
return folderID;
I have the query set to:
"mimeType='application/vnd.google-apps.folder' and '(Team Drive ID)' in parents and name='Folder C' and trashed=false"
but is seems not to traverse the folder structure to find the Folder C folder.
Do I need to have the Folder B folder ID to find the folder or is there a way to have the query search the whole Team Drive for the folder?
I have been working on the following project, some background:
I am an intern currently developing a new search system for my organization. The current setup is microsoft sharepoint 2013 in which the users upload files etc.. and on the other hand is the system I am developing which indexes all data being uploaded to apache SOLR.
I have been succesfull in mapping the sharepoint content repository to a network drive, and I can manually start my program to start indexing the conent of this network drive to SOLR using the Solrj api.
The problem I am facing however is that I am unable to poll events from this network drive. In my test build which ran local I used a watcher service to launch code (reindex documents, delete indexes) on file create, file modify and file delete.
This does not work unfortunantly with a url pointing to a network drive :(.
So the big question: Is there any API / library available for polling events from network drives?
Any help would be extemely appreciated !
So I fnally figured this one out, tried looking at .net's variant of the watcher service (system.io.filesystemwatcher) and i was having the same problem. I finally got it working by using java.io.FileAlterationMonitor / observer.
Code:
public class UNCWatcher {
// A hardcoded path to a folder you are monitoring .
public static final String FOLDER =
"A:\\Department";
public static void main(String[] args) throws Exception {
// The monitor will perform polling on the folder every 5 seconds
final long pollingInterval = 5 * 1000;
File folder = new File(FOLDER);
if (!folder.exists()) {
// Test to see if monitored folder exists
throw new RuntimeException("Directory not found: " + FOLDER);
}
FileAlterationObserver observer = new FileAlterationObserver(folder);
FileAlterationMonitor monitor =
new FileAlterationMonitor(pollingInterval);
FileAlterationListener listener = new FileAlterationListenerAdaptor() {
// Is triggered when a file is created in the monitored folder
#Override
public void onFileCreate(File file) {
try {
// "file" is the reference to the newly created file
System.out.println("File created: "
+ file.getCanonicalPath());
if(file.getName().endsWith(".docx")){
System.out.println("Uploaded resource is of type docx, preparing solr for indexing.");
}
} catch (IOException e) {
e.printStackTrace(System.err);
}
}
// Is triggered when a file is deleted from the monitored folder
#Override
public void onFileDelete(File file) {
try {
// "file" is the reference to the removed file
System.out.println("File removed: "
+ file.getCanonicalPath());
// "file" does not exists anymore in the location
System.out.println("File still exists in location: "
+ file.exists());
} catch (IOException e) {
e.printStackTrace(System.err);
}
}
};
observer.addListener(listener);
monitor.addObserver(observer);
System.out.println("Starting monitor service");
monitor.start();
}
}
On Windows 8, could someone please help me create a script to move some images from a particular folder to another folder?
The file path that lists the images i want to move (not all images) from the folder are listed in this file: C:\Users\Emmanuel\Desktop\test.txt
The folder in which contains some of the images I want removed appear in this folder:
C:\Users\Computer\Desktop\Images1
The folder in which I want the images to be moved to is this folder:
C:\Users\Computer\Desktop\Images2
Your help will be much appreciated
Try this where SourcesFile is your test.txt and DestFolder is the destination.
public int Run()
{
if (!File.Exists(SourcesFile))
{
throw new ArgumentException("Source folder does not exist");
}
if (!Directory.Exists(DestFolder))
{
Console.WriteLine("Destination folder doesn't exist");
Console.WriteLine("Creating destination folder...");
Directory.CreateDirectory(DestFolder);
}
string[] files = File.ReadAllLines(SourcesFile);
Console.WriteLine("Moving {0} files...", files.Length);
foreach (string file in files)
{
string dest = Path.Combine(DestFolder, Path.GetFileName(file));
if (File.Exists(dest))
{
string newFilename = string.Format("{0}_{1}{2}",
Path.GetFileNameWithoutExtension(file),
Guid.NewGuid().ToString("N"),
Path.GetExtension(file));
string newDest = Path.Combine(DestFolder, newFilename);
Console.WriteLine("File {0} already exists, copying file to {1}", file, newDest);
File.Move(file, newDest);
continue;
}
File.Move(file, dest);
}
return 0;
}
I have some code that saves an xml file to the file system.
public static void Save(T obj, string FileName)
{
if (Application.Current.HasElevatedPermissions)
{
string myDocuments = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
string path = System.IO.Path.Combine(myDocuments, FileName);
using (var writer = new StreamWriter(path))
{
var serializer = new XmlSerializer(typeof(T));
serializer.Serialize(writer, obj);
writer.Flush();
}
}
else
{
throw new Exception("Cannot Save File. Application Requires Elevated permissions.");
}
}
While debugging using Internet Explorer 10 the file is not saved to the listed path in the path variable "C:\Users\Travis\Documents\Save.xml"
I call load with the exact same path "C:\Users\Travis\Documents\Save.xml" and the file loads correctly but the file still does not exist at the listed location.
I searched the file system with no results for Save.xml but it has to exist since it is able to load after application exit.
If I access the same page using Chrome the file is created successfully at the location.
I am wondering where Internet Explorer saves the file?
I found that if I uncheck "Enable Protected Mode" in IE's Security tab then the file is created in the location as expected.
I have a windows service (and verified the code by creating a similar WinForms application) where the NotifyFilter doesn't work. As soon as I remove that line of code, the service works fine and I can see the event-handler fire in the WinForms application.
All I'm doing is dropping a text file into the input directory for the FileSystemWatcher to kick off the watcher_FileChanged delegate. When I have the _watcher.NotifyFilter = NotifyFilters.CreationTime; in there, it doesn't work. When I pull it out, it works fine.
Can anyone tell me if I'm doing something wrong with this filter?
Here is the FSW code for the OnStart event.
protected override void OnStart(string[] args)
{
_watcher = new FileSystemWatcher(#"C:\Projects\Data\Test1");
_watcher.Created += new FileSystemEventHandler(watcher_FileChanged);
_watcher.NotifyFilter = NotifyFilters.CreationTime;
_watcher.IncludeSubdirectories = false;
_watcher.EnableRaisingEvents = true;
_watcher.Error += new ErrorEventHandler(OnError);
}
private void watcher_FileChanged(object sender, FileSystemEventArgs e)
{
// Folder with new files - one or more files
string folder = #"C:\Projects\Data\Test1";
System.Console.WriteLine(#"C:\Projects\Data\Test1");
//Console.ReadKey(true);
// Folder to delete old files - one or more files
string output = #"C:\Temp\Test1\";
System.Console.WriteLine(#"C:\Temp\Test1\");
//Console.ReadKey(true);
// Create name to call new zip file by date
string outputFilename = Path.Combine(output, string.Format("Archive{0}.zip", DateTime.Now.ToString("MMddyyyy")));
System.Console.WriteLine(outputFilename);
//Console.ReadKey(true);
// Save new files into a zip file
using (ZipFile zip = new ZipFile())
{
// Add all files in directory
foreach (var file in Directory.GetFiles(folder))
{
zip.AddFile(file);
}
// Save to output filename
zip.Save(outputFilename);
}
DirectoryInfo source = new DirectoryInfo(output);
// Get info of each file into the output directory to see whether or not to delete
foreach (FileInfo fi in source.GetFiles())
{
if (fi.CreationTime < DateTime.Now.AddDays(-1))
fi.Delete();
}
}
I've been having trouble with this behavior too. If you step through the code (and if you look at MSDN documenation, you'll find that NotifyFilter starts off with a default value of:
NotifyFilters.FileName | NotifyFilters.DirectoryName | NotifyFilters.LastWrite
So when you say .NotifyFilter = NotifyFilters.CreationTime, you're wiping out those other values, which explains the difference in behavior. I'm not sure why NotifyFilters.CreationTime is not catching the new file... seems like it should, shouldn't it!
You can probably just use the default value for NotifyFilter if it's working for you. If you want to add NotifyFilters.CreationTime, I'd recommend doing something like this to add the new value and not replace the existing ones:
_watcher.NotifyFilter = _watcher.NotifyFilter | NotifyFilters.CreationTime;
I know this is an old post but File Creation time is not always reliable. I came across a problem where a Log file was being moved to an archive folder and a new file of the same name was created in it's place however the file creation date did not change, in fact the meta data was retained from the previous file (the one that was moved to the archive) .
Windows has this cache on certain attributes of a file, file creation date is included. You can read the article on here: https://support.microsoft.com/en-us/kb/172190.