NotifyFilter of FileSystemWatcher not working - windows

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.

Related

Saving custom Word document using FilePicker in Windows Store app

I am making a Windows Store application and I want to allow users that press an "Export To Word" button to have all the data that they have input into the app to be displayed in a Word document and saved to a desired location on their computer. The code below is a test segment of code that almost does what I am after, however after saving the document and opening it using Word rather than the app, it cannot open the file due to it being corrupted apparently. However when you open it in Notepad the text is displayed as I want.
private async void exportToWord_Click(object sender, RoutedEventArgs e)
{
await ExportToWord();
}
private async Task ExportToWord()
{
// Create the picker object and set options
Windows.Storage.Pickers.FileSavePicker savePicker = new Windows.Storage.Pickers.FileSavePicker();
savePicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary;
// Dropdown of file types the user can save the file as
savePicker.FileTypeChoices.Add("Word", newList<string>{".docx"});
// Default file name if the user does not type one in or select a file to replace
savePicker.SuggestedFileName = "Test";
Windows.Storage.StorageFile file = await savePicker.PickSaveFileAsync();
MessageDialog mD;
if (file != null)
{
// Prevent updates to the remote version of the file until we finish
// making changes and call CompleteUpdatesAsync.
Windows.Storage.CachedFileManager.DeferUpdates(file);
// write to file
await Windows.Storage.FileIO.WriteTextAsync(file, createContentsOfFile());
// Let Windows know that we're finished changing the file so the other
// app can update the remote version of the file.
// Completing updates may require Windows to ask for user input.
Windows.Storage.Provider.FileUpdateStatus updateStatus = await Windows.Storage.CachedFileManager.CompleteUpdatesAsync(file);
if (updateStatus == Windows.Storage.Provider.FileUpdateStatus.Complete)
{
mD = newMessageDialog("Connect exported to:" + file, "Export Successful");
}
else
{
mD = newMessageDialog("Could not save file. Try again", "Export Unsuccessful");
}
}
else
{
mD = newMessageDialog("Operation canceled because the file could not be found. Try again", "Export Unsuccessful");
}
await mD.ShowAsync();
}
private string createContentsOfFile()
{
return "Testing...";
}
I believe the issue is that I am outputting plain text to the Word document but it needs to be in a certain format to be output correctly and be displayed in a Word doc. Is there any way of doing this in Windows Store apps?
Any help would be appreciated.
I'm not aware of any Word doc components available for Windows Runtime apps (Microsoft doesn't provide one, but there could be a third party component I'm not aware of).
You can get documentation on the docx format and for simple text it may not be too complex (I'm not sure), or you can use another format which Word can open.
If you don't need formatting I'd probably stick with txt.
If you need small amounts of formatting then rtf is a good option. It is fairly simple to generate yourself or the RichEditBox can export RTF format text which you can then save into a .doc file and open in Word.

How can use FTP in OBEX to deleting and copying a file into destination Device via bluetooth java code?

I need to replace a file with old version of it in destination device via bluetooth.
I know that OBEX(FTP and OPP) profiles is necessary to use for this.
But I don't know How can delete old version and copy new version of file in destination directory (java code).
Can you help me please?
To perform operations on files you whould firstly change to the directory where the file is.
For exampe, if you need to get to /root/directory/subdir/
you should call setPath three times
setPath(""); // to get to /root/
setPath("directory") // get to /root/directory/
setPath("subdir") // get to root/directory/subdir/
All the code written below is for J2ME
I use this method to set the path with separators (e.g. /root/dir/)
private void moveToDirectory(String dir) throws IOException {
RE r = new RE("/"); // where RE is me.regexp.RE
setDir("");
String[] dirs = r.split(dir);
for (int i = 1; i < dirs.length; i++) setDir(dirs[i]);
}
To delete a file you should open a PUT operation on it and close it, or use the delete method in ClientSession.
public void delete() throws IOException {
HeaderSet hs = cs.createHeaderSet(); // where cs is an opened ClientSession
hs.setHeader(HeaderSet.NAME, file); // file - is a filename String, no slashes should be used
cs.delete(hs);
}
If you need to replace a file you probably don't need to call delete method, just open OutputStream and write to it a new one
public OutputStream openOutputStream() throws IOException {
HeaderSet hs = cs.createHeaderSet();
hs.setHeader(HeaderSet.NAME, file);
Operation op = cs.put(hs); // Operation should be global, so you can close it after you done
return op.openOutputStream();
}
remember to close Operation after you done with the streams.

How to design my mapper?

I have to write a mapreduce job but I dont know how to go about it,
I have jar MARD.jar through which I can instantiate MARD objects.
Using which I call the mard.normalize file meathod on it i.e. mard.normaliseFile(bunch of arguments).
This inturn creates certain output file.
For the normalise meathod to run it needs a folder called myMard in the working directory.
So I thought that I would give the myMard folder as the in input path to hadoop job, but m not sure if that would help beacuse mard.normaliseFile(bunch of arguments) will search for the myMard folder in the working directory but it will not find it as (**this is what I think) the Mapper will only be able to access the content of files through the "values" obtained from the fileSplit, it cannot give direct access to the files in the myMard folder.
In short I have to execute the follwing code through the MapReduce
File setupFolder = new File(setupFolderName);
setupFolder.mkdirs();
MARD mard = new MARD(setupFolder);
Text valuz = new Text();
IntWritable intval = new IntWritable();
File original = new File("Vca1652.txt");
File mardedxml = new File("Vca1652-mardedxml.txt");
File marded = new File("Vca1652-marded.txt");
mardedxml.createNewFile();
marded.createNewFile();
NormalisationStats stats;
try {
stats = mard.normaliseFile(original,mardedxml,marded,50.0);
//This meathod requires access to the myMardfolder
System.out.println(stats);
} catch (MARDException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Please help

Custom Event Receiver - Copy To Folder

I am in the process of writing a custom event receiver. The basic flow is as follows:
Document is added to Library
Based on metadata of document, we check to see if a folder within another document library exists.
If the folder does not exist, it is created.
The newly added document is copied to the folder residing in another document library.
I have got myself to the point, where I can copy newly added files, from one document library to another when they are added. However I cannot figure out how to copy to a specific directory (by name) within a document library. Any help would be greatly received.
Here is my code so far:
SPFile sourceFile = properties.ListItem.File;
SPFile destFile; // Copy file from source library to destination
using (Stream stream = sourceFile.OpenBinaryStream())
{
var destLib = (SPDocumentLibrary) properties.ListItem.Web.Lists[listName];
destFile = destLib.RootFolder.Files.Add(sourceFile.Name, stream);
stream.Close();
}
// Update item properties
SPListItem destItem = destFile.Item;
SPListItem sourceItem = sourceFile.Item;
// Copy meta data
destItem["Title"] = sourceItem["Title"];
//...
//... destItem["FieldX"] = sourceItem["FieldX"];
//...
destItem.UpdateOverwriteVersion();
Answer
//Ensure folder here
var destFolder = destLib.RootFolder.SubFolders["name"];
destFile = destFolder.Files.Add(sourceFile.Name, stream);

IsolatedFileStorage XML Reading Crash

Ok so, basically my problem is with reading and XML file from IsolatedFileStorage. I'll go through the process that leads to my error and then I'll list the relevant code and XML file.
On the first execution it recognises that the file does not exist - it therefore creates the file in IsolatedFileStorage
On the second execution it can now see that the file does exist and so it loads the XML file
On the third execution it can see that it exists - but it throws an XML error
I cannot for the life of me find a solution to it (link to other discussion on MSDN here)
So the code for reading/creating the XML file in IsolatedFileStorage is as follows:
try
{
/***********************
* CHECK THE SETTINGS
********************/
if (store.FileExists("AppSettings.xml"))
{
streamSettings = new IsolatedStorageFileStream("AppSettings.xml", System.IO.FileMode.Open, store);
DebugHelp.Text = "AppSettings.xml exists... Loading!";
streamSettings.Seek(0, System.IO.SeekOrigin.Begin);
xmlDoc = XDocument.Load(streamSettings, LoadOptions.None);
}
else
{
streamSettings = new IsolatedStorageFileStream("AppSettings.xml", System.IO.FileMode.Create, store);
DebugHelp.Text = "AppSettings.xml does not exist... Creating!";
xmlDoc = XDocument.Load("AppSettings.xml", LoadOptions.None);
}
if (xmlDoc != null)
xmlDoc.Save(streamSettings);
}
catch (Exception e)
{
DebugHelp.Text = e.ToString();
}
finally
{
streamSettings.Close();
}
And the related XML file is as follows:
<?xml version="1.0" encoding="utf-8" ?>
<Settings>
</Settings>
Extremely advanced I know - however it throws the following error (here) and you can find the full error text at the bottom of the Social.MSDN page.
Please help - I have been looking for a solution (as the one on the social.msdn site didn't work) for about 2 weeks now.
Why don't you try to read file using a simple StreamReader ? Below a part of a method I have created to readfile from store. Have a try, check your content, and then try loading xml from String (XDocument.Parse etc ...)
String fileContent = String.Empty;
using (_store = IsolatedStorageFile.GetUserStoreForApplication())
{
if (_store.FileExists(file))
{
_storeStream = new IsolatedStorageFileStream(file, FileMode.Open, _store);
using (StreamReader sr = new StreamReader(_storeStream))
{
fileContent = sr.ReadToEnd();
}
__storeStream.Close();
return fileContent;
}
else {
return null;
}
}
It looks to me like the problem is in your save method - it looks like you are maybe appending the settings each time you close - to overwrite your existing settings, you need to ensure that you delete your existing file and create a new one.
To help debug this, try using http://wp7explorer.codeplex.com/ - this might help you see the raw file "on disk"
As an aside, for settings in general, do check out the AppSettings that IsolatedStorage provides by default - unless you have complicated needs, then these may suffice on their own.
Your code sample isn't complete so it's hard to say for sure but, rather than just seeking to the start of the file you may find it easier to just delete it if it already exists. You can do this with FileMode.Create. In turn this means you can do away with the need to check for the existing file.
I suspect that the problem is that you are writing a smaller amount of text to the file on subsequent attempts and so leaving part of the original/previous text behind. In turn this creates a file which contains invalid XML.

Resources