create folder firing two times - c#

My app two way sync app when iam created new folder from desktop it is some time creating extra folder with name "New folder "
private void FileSystemWatcherCreated(object sender, FileSystemEventArgs e)
{
try
{
var parentDirectory = Directory.GetParent(e.FullPath).FullName;
if (!this.IsWatchedObject(e.FullPath))
{
return;
}
if (!this.IsFileOrDirectoryExists(e.FullPath))
{
if (!string.IsNullOrWhiteSpace(e.FullPath))
{
this.Debug("FileSystemWatcherCreated", "Delete '{0}' from the icon overlay system...", e.FullPath);
var success = CloudFuzeIconOverlayAssystent.DeleteFileFolderRecord(e.FullPath, true, this.LogService);
this.Debug("FileSystemWatcherCreated", success.BooleanToSuccessFailLogString());
this.SendFileSystemItemChangedRecursively(e.FullPath);
}
return;
}
else
{
if (Directory.Exists(e.FullPath))
{ //http://stackoverflow.com/questions/16301598/filesystemwatcher-files-in-subdirectory
foreach (string file in Directory.GetFiles(e.FullPath))
{
var eventArgs = new FileSystemEventArgs(
WatcherChangeTypes.Created,
Path.GetDirectoryName(file),
Path.GetFileName(file));
FileSystemWatcherCreated(sender, eventArgs);
}
}
}
if (this.IsFileFolderAddedToRootFolder(this.cloudFuzeDirectory, e.FullPath))
{
return;
}
if (this.cloudFuzeDirectory == parentDirectory)
{
return;
}
var type = Directory.Exists(e.FullPath) ? WellKnownFileFoderTypes.Folder : WellKnownFileFoderTypes.File;
this.Debug("FileSystemWatcherCreated", "Add '{0}' in the queue for registration in the local storage...", e.FullPath);
this.addedFileFolders.Enqueue(new FileFolder
{
SavedFilePath = e.FullPath,
FileType = type,
Type = type
});
}
catch (Exception exc)
{
this.Error("FileSystemWatcherCreated", exc);
}
}

Related

Running macro to open file window in another program, need if statement that will execute when file is saved (c#)

private void pdfButton_Click(object sender, EventArgs e)
{
Operation.RunMacro("ExportPDF.cs");
if (Operation.RunMacro == )
{
MessageBox.Show("PDF files exported!");
pdfLabel.Text = pdfLabel.Text + " - DONE!";
pdfLabel.ForeColor = System.Drawing.Color.Green;
}
else
{
pdfLabel.Text = pdfLabel.Text + " WRONG!";
pdfLabel.ForeColor = System.Drawing.Color.Red;
}
}
This is my body of code, when the pdfButton is clicked, the macro will run opening up my file window. From there the user names their files and stores to a folder, how can I make the if statement execute when they store their files?
The method Operation.RunMacro needs to return the operation result. Then you have a condition you can test against:
class Operation
{
public bool RunMarco(string fileName)
{
try
{
// export logic
...
return true;
}
catch
{
return false;
}
}
}
then you can do:
private void pdfButton_Click(object sender, EventArgs e)
{
bool runMacroResult = Operation.RunMacro("ExportPDF.cs");
if (runMacroResult)
{
MessageBox.Show("PDF files exported!");
pdfLabel.Text = pdfLabel.Text + " - DONE!";
pdfLabel.ForeColor = System.Drawing.Color.Green;
}
else
{
pdfLabel.Text = pdfLabel.Text + " WRONG!";
pdfLabel.ForeColor = System.Drawing.Color.Red;
}
}

c# updater help ( restart once update is complete )

Hello all i have managed to make a basic program that will do a update for me but one thing i want to try and do when the update form is open to close the main form then restart program when the update is finished but have no idea how to do this
this is the code i have currently
namespace update_test
{
public partial class Form1 : Form
{
// folder calls needed
string updatepath = Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + "updatetest");
public Form1()
{
InitializeComponent();
}
// copying files
private static void DirectoryCopy(
string sourceDirName, string destDirName, bool copySubDirs)
{
DirectoryInfo dir = new DirectoryInfo(sourceDirName);
DirectoryInfo[] dirs = dir.GetDirectories();
// If the source directory does not exist, throw an exception.
if (!dir.Exists)
{
throw new DirectoryNotFoundException(
"Source directory does not exist or could not be found: "
+ sourceDirName);
}
// If the destination directory does not exist, create it.
if (!Directory.Exists(destDirName))
{
Directory.CreateDirectory(destDirName);
}
// Get the file contents of the directory to copy.
FileInfo[] files = dir.GetFiles();
foreach (FileInfo file in files)
{
// Create the path to the new copy of the file.
string temppath = Path.Combine(destDirName, file.Name);
// Copy the file.
file.CopyTo(temppath, true);
}
// If copySubDirs is true, copy the subdirectories.
if (copySubDirs)
{
foreach (DirectoryInfo subdir in dirs)
{
// Create the subdirectory.
string temppath = Path.Combine(destDirName, subdir.Name);
// Copy the subdirectories.
DirectoryCopy(subdir.FullName, temppath, copySubDirs);
}
}
}
public void downloadfile()
{
//client.DownloadFile("http://elfenliedtopfan5.co.uk/update/elfenlied_weapons.zip", updatepath);
WebClient client = new WebClient();
string file = Path.Combine(updatepath, "elfenlied_weapons.zip");
client.DownloadFileAsync(new Uri("http://elfenliedtopfan5.co.uk/update/elfenlied_weapons.zip"), file);
client.DownloadProgressChanged += client_DownloadProgressChanged;
MessageBox.Show(file);
}
void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
int bytesin = int.Parse(e.BytesReceived.ToString());
int totalbytes = int.Parse(e.TotalBytesToReceive.ToString());
int kb1 = bytesin / 1024;
int kb2 = totalbytes / 1024;
label1.Text = kb1.ToString() + "KB out of " + kb2.ToString() + "KB (" +e.ProgressPercentage.ToString() + "%)";
progressBar1.Value = e.ProgressPercentage;
if (e.ProgressPercentage == 100)
{
exactzip();
}
}
public void update()
{
string downloadurl = "";
Version newversion = null;
string xmlurl = "http://elfenliedtopfan5.co.uk/xml/update.xml";
XmlTextReader reader = null;
try
{
reader = new XmlTextReader(xmlurl);
reader.MoveToContent();
string elementname = "";
if ((reader.NodeType == XmlNodeType.Element)&& (reader.Name == "update_test"))
{
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element)
{
elementname = reader.Name;
}
else
{
if((reader.NodeType == XmlNodeType.Text)&& (reader.HasValue))
{
switch (elementname)
{
case "version":
newversion = new Version(reader.Value);
break;
case "url":
downloadurl = reader.Value;
break;
}
}
}
}
}
}
catch(Exception e)
{
MessageBox.Show(e.Message);
}
finally
{
if (reader != null)
reader.Close();
}
Version applicationvershion = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
if (applicationvershion.CompareTo(newversion) < 0)
{
DialogResult dialogResult = MessageBox.Show("Version " + newversion.Major + "." + newversion.Minor + "." + newversion.Build + " of elfenliedprograms do you want to update now ?", "Update Avalible!", MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.Yes)
{
var myForm = new Form1();
myForm.Show();
}
else if (dialogResult == DialogResult.No)
{
//do something else
}
else
{
MessageBox.Show("program currently upto date :) ");
}
}
}
public void seeiffile()
{
// Set to folder path we must ensure exists.
string updatepathex = updatepath;
try
{
// If the directory doesn't exist, create it.
if (!Directory.Exists(updatepathex))
{
Directory.CreateDirectory(updatepathex);
}
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
// if all above works then follow this
public void exactzip()
{
using (ZipFile zip = ZipFile.Read (Path.Combine(updatepath, "elfenlied_weapons.zip")))
{
foreach (ZipEntry e in zip)
{
e.ExtractExistingFile = ExtractExistingFileAction.OverwriteSilently;
e.Extract(updatepath);
// e.Extract(updatepath);
}
}
}
private void button1_Click(object sender, EventArgs e)
{
seeiffile();
downloadfile();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void Form2_FormClosing(object sender, FormClosingEventArgs e)
{
ShowHideForm1(true);
}
private void ShowHideForm1(bool show)
{
Form1 f1 = Application.OpenForms.OfType<Form1>().SingleOrDefault();
if (f1 != null)
{
if (show)
{ f1.Show(); }
else
{ f1.Hide(); }
}
}
private void Form2_Shown(object sender, EventArgs e)
{
ShowHideForm1(false);
}
}
}
then i have another form attached to this application called
elfenliedprograms.cs
witch contains this code
namespace update_test
{
public partial class elfenliedprograms : Form
{
public elfenliedprograms()
{
InitializeComponent();
}
private void elfenliedprograms_Load(object sender, EventArgs e)
{
update();
}
public void update()
{
string downloadurl = "";
Version newversion = null;
string xmlurl = "http://elfenliedtopfan5.co.uk/xml/update.xml";
XmlTextReader reader = null;
try
{
reader = new XmlTextReader(xmlurl);
reader.MoveToContent();
string elementname = "";
if ((reader.NodeType == XmlNodeType.Element) && (reader.Name == "update_test"))
{
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element)
{
elementname = reader.Name;
}
else
{
if ((reader.NodeType == XmlNodeType.Text) && (reader.HasValue))
{
switch (elementname)
{
case "version":
newversion = new Version(reader.Value);
break;
case "url":
downloadurl = reader.Value;
break;
}
}
}
}
}
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
finally
{
if (reader != null)
reader.Close();
}
Version applicationvershion = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
if (applicationvershion.CompareTo(newversion) < 0)
{
DialogResult dialogResult = MessageBox.Show("Version "+ newversion.Major + "." + newversion.Minor + "." + newversion.Build + " of elfenliedprograms do you want to update now ?", "Update Avalible!", MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.Yes)
{
var myForm = new Form1();
myForm.Show();
}
else if (dialogResult == DialogResult.No)
{
//do something else
}
else
{
MessageBox.Show("program currently upto date :) ");
}
}
}
so basically once the update triggers there is a update it will call elfenliedprograms.cs but it will not shut down the main form if i do that it will shut the whole process down and im not sure how to go about making it download then restart app so all new stuff is updated it has taken me a good 4 months just to get this working the way i want not very good when it comes to updating a aplication so i would need help on this part sorry to be a pain and ask
thank you for

Context Menu item not showing

I am trying to place a new Menuitem in Explorer context menu and I cannot get it to work.
I am not getting any exceptions or error messages and I've set breakpoints and they're not being hit. And I've searched the registry and it's not there. What am I doing wrong?
private const string MenuName = "Folder\\shell\\NewMenuOption";
private const string Command = "Folder\\shell\\NewMenuOption\\command";
private void Form1_Shown(object sender, EventArgs e)
{
using(var folder = new FolderBrowserDialog())
{
if(folder.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
Properties.Settings.Default.ArchivePath = folder.SelectedPath;
Properties.Settings.Default.Save();
RegistryKey regmenu = null;
RegistryKey regcmd = null;
try
{
regmenu = Registry.ClassesRoot.CreateSubKey(MenuName);
if (regmenu != null)
regmenu.SetValue("", "Archive");
regcmd = Registry.ClassesRoot.CreateSubKey(Command);
if (regcmd != null)
regcmd.SetValue("", Environment.CurrentDirectory + #"\Archiver.exe");
}
catch (Exception ex)
{
MessageBox.Show(this, ex.ToString());
}
finally
{
if (regmenu != null)
regmenu.Close();
if (regcmd != null)
regcmd.Close();
}
}
else
{
if(MessageBox.Show("In order to use Archiver, you must first specify where your archive is. Do you want to continue?", "Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1) == System.Windows.Forms.DialogResult.Yes)
{
Application.Restart();
}
else
{
this.Dispose(true);
}
}
}
}
Run your app as admin.
Making changes to the register may require admin rights.

My method did not add my file into my list although no error

This is my class that after each file choose add the file to my list and from the main form raise event that update my ListBox and add the file into my ListBox.
when i am choosing 2 files i can see (with the debugger) that the add method add the first file and my list updated but after the second file pass the add method the list.count remained still 1.
public class ListboxFile
{
public delegate void OnFileAdd(string file);
public event OnFileAdd OnFileAddEvent;
private static List<string> _files;
public ListboxFile()
{
_files = new List<string>();
}
public void add(string file)
{
_files.Add(file);
OnFileAddEvent(file);
}
public void remove(string file)
{
if (_files.Contains(file))
{
_files.Remove(file);
}
}
public void clear()
{
_files.Clear();
}
public List<string> list
{
get { return _files; }
}
}
from the main form (add files button click):
private void btnAddfiles_Click(object sender, EventArgs e)
{
#region file filter
string fileToAdd = string.Empty;
System.IO.Stream stream;
OpenFileDialog thisDialog = new OpenFileDialog();
thisDialog.InitialDirectory = (lastPath.Length > 0 ? lastPath : "c:\\");
thisDialog.Filter = "(*.snoop, *.pcap, *.cap, *.net, *.pcapng, *.5vw, *.bfr, *.erf, *.tr1)" +
"|*.snoop; *.pcap; *.cap; *.net; *.pcapng; *.5vw; *.bfr; *.erf; *.tr1|" + "All files (*.*)|*.*";
thisDialog.FilterIndex = 1;
thisDialog.RestoreDirectory = false;
thisDialog.Multiselect = true;
thisDialog.Title = "Please Select Source File";
#endregion
if (thisDialog.ShowDialog() == DialogResult.OK)
{
if (thisDialog.FileNames.Length > 0)
{
lastPath = Path.GetDirectoryName(thisDialog.FileNames[0]);
}
BackgroundWorker backgroundWorker = new BackgroundWorker();
backgroundWorker.WorkerReportsProgress = true;
backgroundWorker.DoWork +=
(s3, e3) =>
{
foreach (String file in thisDialog.FileNames)
{
try
{
if ((stream = thisDialog.OpenFile()) != null)
{
int numberOfFiles = thisDialog.SafeFileNames.Length;
using (stream)
{
ListboxFile lbf = new ListboxFile();
lbf.OnFileAddEvent += lbf_OnFileAddEvent;
lbf.checkFile(file);
lastPath = Path.GetDirectoryName(thisDialog.FileNames[0]);
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}
};
backgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(
(s3, e3) =>
{
});
backgroundWorker.RunWorkerAsync();
}
}
private void lbf_OnFileAddEvent(string file)
{
if (InvokeRequired)
{
this.Invoke((MethodInvoker)delegate
{
listBoxFiles.Items.Add(file);
, listBoxFiles.Items.Count.ToString("#,##0")));
if (listBoxFiles.Items.Count != 0)
listBoxFiles.SetSelected(listBoxFiles.Items.Count - 1, true);
});
}
else
{
listBoxFiles.Items.Add(file);
if (listBoxFiles.Items.Count != 0)
listBoxFiles.SetSelected(listBoxFiles.Items.Count - 1, true);
}
}
You declare and initialize the instance of ListBoxFile inside the foreach loop.
At every loop you reinitialize the instance and thus you loose the previous add
A fast fix, move the declaration and initialization of the ListboxFile instance outside the loop (also the subscription to the event)
.....
ListboxFile lbf = new ListboxFile();
lbf.OnFileAddEvent += lbf_OnFileAddEvent;
foreach (String file in thisDialog.FileNames)
{
.....
and by the way, you call lbf.checkFile(file);, did you mean lbf.Add(file) right?
You are calling lbf.checkFile(file); but I do not see that method in your class definition. Maybe inside that method you are not firing OnFileAddEvent?

FileUpload.SaveAs issue

I am saving (uploading) file to FTP server using file upload control and .SaveAs method. But after 1st post back session values are lost. Not sure why and any work around this.
protected void Page_Load(object sender, EventArgs e)
{
if (Session["TheUser"] != null)
{
aUser = (clsUser)Session["TheUser"];
}
}
protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)//continue only if the file control has the file
{
if (Get_and_Show_FileInformation())//if the file information was retrived and loaded into the textboxes
{
//continue with the execution
}
else
{
//error message displyed
}
}
}
protected bool Get_and_Show_FileInformation()
{
if (FileUpload1.HasFile)
{
string fName = FileUpload1.PostedFile.FileName;
string extension = Path.GetExtension(fName);
string FileName = fName.Substring(0, fName.Length - extension.Length);
string dir = uname;
string appPath = Server.MapPath("Uploads/") + dir;
FileInfo MyFileInfo = new FileInfo(appPath);
DirectoryInfo newDirectoryInfo = new DirectoryInfo(appPath);
if (!Directory.Exists(appPath))//if user is uploading to FTP_Upload first time, create a new directory for him/her
{
try
{
FileUpload1.SaveAs(Server.MapPath("~/Uploads/" + dir + "/" + FileName)); // ERROR here, call to this .SaveAs method causes loss of session values (Session["TheUser"])
Image2.ImageUrl = "~/Uploads/" + dir + "/" + FileName;
return true;
}
catch (Exception ex)
{
lbl_Err.Text = "<br/>Error: Error creating and saving into your space!(Error Code:XF05)";
return false;
}
}
else
{
//same code but don't create the directory
}
}
}

Categories