How to use solution explorer files in c# application - c#

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

Related

Drag drop does not work on compiled EXE file

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.

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.

Setup project in c# windows application cant load image?

![enter image description here][1]i have a windows application in C# with a setup project !!!
I used Image.FromFile("filename") in my application but when make a setup project from it , and run it , it dose not show my pictures ! why ?
try
{
string timeOfDay = Convert.ToInt32(DateTime.Now.TimeOfDay.ToString().Substring(3, 2)).ToString();
this.BackgroundImage = Image.FromFile("BackGround\\Flowers (" + timeOfDay + ").jpg");
}
catch (Exception ex)
{
this.BackgroundImage = Image.FromFile("\\BackGround\\Flowers (59).jpg");
}
First you have to add the Image file to your Visual Studio project unless you do this image can not be embedded into the output assembly.
Project Folder > Images
First add a custom folder and move your image to that folder and add the same folder to your VS project. now go to Image property and set the Build Action as "Resource".

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.
}

How to add entity-framework to console application (images are included)

I try to add entity-framework to console application:
I press "add new item" and
then
then
then I added code:
class Program
{
static void Main(string[] args)
{
try
{
Database1Entities db = new Database1Entities();
db.AddToTableTest(new TableTest { name = "name" });
db.SaveChanges();
int count = db.TableTest.Count();
int ui = 9 + 0;
}
catch (Exception e)
{
}
}
}
It gives no error, but I don't see any changes in database.
I described the issue better here
I did the same steps you did to setup a EF model. your database.mdf file has the Copy to Output Directory set to Copy always, that means that every time you hit F5 (build or debug your app) the file is getting replaced by the empty one on your project.
Changing the Copy to Output Directory on the Properties window of the mdf file should solve your problem.
If you use Copy if newer you are going to be persisting any modifications on the contents of the database until you edit the database (mdf) itself.
With Do not copy any change to the mdf file is not going to get reflected on your application and will probably generate problems with EF.
I recommend for this scenario that you use Copy if newer and fill your basic data in the mdf file so you will have it always available.

Categories