Drag drop does not work on compiled EXE file - c#

I added a functionality to my C# windows form application which allows user to drag-drop file on the form so that the application can get the file path. I just exactly followed what's written on:
How to provide file drag-and-drop functionality in a Visual C# application
It is working on debug mode in Visual Studio environment. However, as soon as I try the same thing on individual exe file which is created on bin/Debug folder, the application does not react to drag-drop.
I have already tried to delete all the files on bin/Debug folder, but the result did not change.
It would be great if somebody has similar issue and solutions for this. Thank you.
Here are the codes I'm trying (after some try and errors it has changed a bit from what's written in the URL shown above, but this still works on Visual Studio but not on exe...) :
private void OpenFile_DragEnter(object sender, DragEventArgs e)
// enable drag-drop event
{
e.Effect = DragDropEffects.Copy;
}
private void OpenFile_DragDrop(object sender, DragEventArgs e)
// open drag-dropped setup file
{
// get drag-dropped file path
string[] s = (string[])e.Data.GetData(DataFormats.FileDrop, false);
// open all the files
for (int i = 0; i < s.Length; i++)
{
OpenSetup(s[i]);
}
}
Update: Another thing I found is that I can drag-drop the files on EXE from OpenFileDialog, but not from file exploler.

Related

Where are the settings stored?

NOTE: The "possible duplicate" question refers to a totally and complete different theme (refering to visual studio user settings". This question is not related to that at all. Please verify before marking "possible duplicates"
I am trying to save some settings of my program between calls and I did what this tutorial says.
It works very well. A little too well...
To summarize I created settings.settings file. Then in the form closing file, I wrote code to save the settings
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
Properties.Settings.Default.TheSetting = settingNumber;
Properties.Settings.Default.Save();
}
and in the load function code to retrieve the setting
private void Form1_Load(object sender, EventArgs e)
{
DateTime t = DateTime.Now;
if (Properties.Settings.Default.TheDate.Date == t.Date) //it is today
{
settingNumber = Properties.Settings.Default.TheSetting;
}
else
{
//we start again
settingNumber = 0;
}
textBox1.Text = settingNumber.ToString();
}
I tried and run it several times, now the setting Number is 39.
However, and this is the strange thing this value is not found anywhere. I opened the .exe.config file that is supposed to hold the setting values and they have totally different numbers. Even if I edit them (as in the tutorial) the program still runs with its number.
Where are these setting values stored?
Thanks to user swamy I found the required file.
It was in AppData folder (which is in the corresponding User Folder) then Local, and under the a folder named after the program and the file name is user.config. The path is a really long one
I read that this path can change in other versions

c# Form Project won't save Setting changes of Console Project

Background
Console Application:
I have a console application that retrieves data from a spreadsheet using the google sheets API. This application is automated by running it every 5 minutes with windows scheduler.
Form Application:
In the same solution I have created a windows form project that can be run manually, outside of the automation process to tweak any settings without disturbing the 5 minute process. (i.e. If we want to change spreadsheet ID to fetch data form a different spreadsheet, or if i want to change the output folder of where the data is being fetched)
My Goal
I'm trying to develop a form project that will edit the "settings.settings" file of another project in the same solution. Below is a screenshot of how i have my solution laied out:
What I've done so far
I've already added a reference from my sheetstocsv project in my SettingsUI Project, and i've successfully created a form that accesses sheetstocsv's Settings and edits them when a save button is clicked. Shown below is the function that's supposed to save the new settings from the form.
private void Save_Button_Click(object sender, EventArgs e)
{
sheetstocsv.Properties.Settings.Default.outputdir = OutputDirectory_TextBox.Text;
sheetstocsv.Properties.Settings.Default.spreadsheetID = SpreadsheetID_Textbox.Text;
sheetstocsv.Properties.Settings.Default.Entity = Entity_Texbox.Text;
sheetstocsv.Properties.Settings.Default.headernum = (int)Columns_NumericUpDown.Value;
string headers = "";
for (int i = 0; i < (int)Columns_NumericUpDown.Value; i++)
{
headers = headers + Columns_DataGridView.Rows[0].Cells[i].Value.ToString() + ",";
}
sheetstocsv.Properties.Settings.Default.headers = headers;
sheetstocsv.Properties.Settings.Default.configured = true;
sheetstocsv.Properties.Settings.Default.Save();
MessageBox.Show("Saving Complete!", "Settings",
MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
}
How I'm trying to do it
Below is a code snippet of how i'm only letting the sheetstocsv project continue if the configuration file has configured it first
//Check for if configured
if (Properties.Settings.Default.configured == false)
{
Console.WriteLine("Program has not been configured yet! Please Run SettingsUI first to start this program.");
Console.ReadLine();
Environment.Exit(0);
}
My Problem
Whenever I run my settingsUI, save, and then run my sheetstocsv project the changes that were supposed to be saved are not. and it will not allow the program move foward.
Edit
Below is the full form .cs that shows how i'm editing the properties of the other project
using sheetstocsv;
namespace SettingsUI
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Columns_DataGridView.RowCount = 1;
Columns_DataGridView.ColumnCount =(int)Columns_NumericUpDown.Value;
}
// Event handlers for other UI elemets here.......
private void Save_Button_Click(object sender, EventArgs e)
{
sheetstocsv.Properties.Settings.Default.outputdir = OutputDirectory_TextBox.Text;
sheetstocsv.Properties.Settings.Default.spreadsheetID = SpreadsheetID_Textbox.Text;
sheetstocsv.Properties.Settings.Default.Entity = Entity_Texbox.Text;
sheetstocsv.Properties.Settings.Default.headernum = (int)Columns_NumericUpDown.Value;
string headers = "";
for (int i = 0; i < (int)Columns_NumericUpDown.Value; i++)
{
headers = headers + Columns_DataGridView.Rows[0].Cells[i].Value.ToString() + ",";
}
sheetstocsv.Properties.Settings.Default.headers = headers;
sheetstocsv.Properties.Settings.Default.configured = true;
sheetstocsv.Properties.Settings.Default.Save();
MessageBox.Show("Saving Complete!", "Settings", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
}
}
}
I don't quite have enough info from your question (see comment from Rufus), but I am guessing that your console app launches your WinForm? If this is the case, what is likely happening is this:
1) Console app starts, and loads the config file into memory.
2) Your Winform launches and changes the config file.
3) Console app overwrites the changes to the config file on exit since it read it before the changes were made.
You could just move the winform into your console project, then just do something like this:
Properties.Settings.Default.outputdir = OutputDirectory_TextBox.Text;
...
Adding More Info (Oct 1):
I must be honest, doing what you're doing is a little strange, and I would really rethink referencing an executable to change its default settings. Just because VS lets you do this, doesn't necessarily mean you should. But if you must, there are a couple other things you can try:
1) You can simply parse the xml settings file and change node values of the settings you want to change. System.Xml namespace will make very short work of this. The post below has good examples:
Change xml node value
2) Try wrapping the code that is currently in your button click event handler with some method inside the console project. This way, you're calling a method that changes the settings, rather than trying to change the settings from an external assembly.
Note: neither of those methods will work if your console app is running while you're making changes to its config file. On shut down, the console app will overwrite the settings file with the settings it loaded into memory when it started up. If the console app isn't running, 1) will definitely work.

How to use solution explorer files in c# application

I've developed a small application in c#. In this application i've added a text file named Data.txt and folder with about 20 images numbered from 1 - 20 in the solution explorer so that these are hidden from user and embedded in application. I've set these files properties to "None" and CopyToOutput "false" (also tried Property to "Content").
The problem is that when i debug my program on my Windows 8.1 laptop pc which contains my project and files, it works well but when i try to run the release files (also tried debug files) on my Win 7 Home Basic desktop pc, it stops working (means it doesn't load those files). Here is my code :
// Code to change images in picture box after small interval of time
private void timer1_Tick(object sender, EventArgs e)
{
try
{
if (Angle > 20)
{
Angle = 1;
}
picBackground.BackgroundImage.Dispose();
picBackground.BackgroundImage = new Bitmap("../../" + Angle + ".png");
Angle += 5;
}
catch
{ }
}
// Here is constructor of the class
public RateFiles()
{
try
{
string[] data = File.ReadAllLines("../../Data.txt");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString(), "Error");
}
// Object loads the strings
obj.LoadData(data);
}
The Picture Box Background is required to change after 1 second but it is not working and File.ReadAllLines("../../Data.txt") is giving error "Could not find file 'C:\Users\Dell\Data.txt'".
How can I resolve this problem?
The problem is that you are trying to both access the files as if you were distributing the files outside of the assembly, and setting them not to copy which excludes them from the files to be distributed.
To do what you want, you need to set the files up as resources, and then access them as such in your application. Try the following link to read up on how to create and access resources in C# with VS.
https://msdn.microsoft.com/en-us/library/7k989cfy%28v=vs.90%29.aspx

getting the full filenames from all top directory files in a specific directory and suppressing the occuring error

I met a not expected problem with getting just the top directory full filenames from a specific directory. C# throws an error and doesn't list anything in the specific directory.
But MS DOS has not a problem with my command: *"dir C:\windows\prefetch\*.pf"
Visual Basics 6 old "Dir Function" also does it without complaining.
The "Windows Explorer" opens it up and doesn't ask anything from me. Also "Nirsofts Tool Suit" lists it instantly without any problem. No one of this tools needs to run with special permissions, just a double click on the application icon and ready is the task.
I looked around and found nothing here, what would answer this weird problem. My user can access the directory, if I go with any other application into it, now there is the question why C# throws
an "Unauthorized Access Exception" which is totally weird, since I have access in this folder.
I don't want to elevate my application with admin permissions for it nor create extra a xml for it to run it with highest privileges. The not trustful yellow elevation box must be avoided.
Now my question: How it comes that I can not list the filenames in this folder when all other
applications can do that.
What code do I need if "Directory.GetFiles()" fails?
Is there any flag or property in the framework directory class which allows my application access to the files, whatever.
Here my code which fails (using System.IO):
private void button1_Click(object sender, EventArgs e)
{
textBox1.Text = textBox1.Text.Substring(0, 0); //clear the textBox1
//Unauthorized access exception and yellow bar in this line
foreach(string FileX in Directory.GetFiles(Path.Combine(Environment.GetEnvironmentVariable("windir"), "prefetch"), "*.pf"))
{
textBox1.Text += FileX;
}
}
Did I understand correctly that you only need the File-names with directory-names.
This code works for me, no elevations needed.
private void button1_Click(object sender, EventArgs e)
{
string folder = #"C:\windows\prefetch";
string filemask = #"*.pf";
string[] filelist = Directory.GetFiles(folder, (filemask));
//now use filelist[i] for any operations.
}

C#, working with files, "Unauthorized Access"?

I'm learning about opening and saving files with C# and it seems that vista won't let my program save to a file on the root of C:\ , unless I run it in administrator mode.
Any ideas how to allow my program to play around with whatever files it wants?
Thanks!
private string name;
private void open_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
name = openFileDialog1.FileName;
textBox1.Clear();
textBox1.Text = File.ReadAllText(name);
textBox2.Text = name;
}
}
private void save_Click(object sender, EventArgs e)
{
File.WriteAllText(name, textBox1.Text);
}
To make your program start with administrator rights, you have to change the manifest. This can be done by Add New Item -> General -> Application Manifest File. Open the manifest and set "requestedExecutionLevel" to "requireAdministrator". When this is done, open the project settings and on the 'Application' tab choose your new manifest.
The program will run with your credentials, by default.
So, these do not have the right permissions to write to the root folder.
If you want it to run with other credentials you can us the runas command line to execute the application with other credentials.
Alternatively, grant more permissions to the account the application runs as.
There are several reasons for the UnauthorizedAccess Exception. Check one of those:
path specified a file that is read-only.
This operation is not supported on the current platform.
path specified a directory.
I accidently hit the third problem today ;-)

Categories