Setup project in c# windows application cant load image? - c#

![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".

Related

Trying Upload same file in windows form

I am working to develop a Windows form Project, we should use a Product picture.
Every this working well, we use File.Exists() to check if the file already exists then copy the image to the product Image folder.
if (image.ShowDialog() == DialogResult.OK && !string.IsNullOrEmpty(image.FileName))
{
_view.FirmLogo.Image = new Bitmap(image.FileName);
_view.LogoURL = Path.Combine(System.IO.Path.GetFullPath(#"..\..\"), #"Resources\ProductImage\", Path.GetFileName(image.FileName));
//
if (File.Exists(_view.LogoURL))
{
File.Delete(_view.LogoURL);
}
//File.Move(#"c:\test\SomeFile.txt", #"c:\test\Test\SomeFile.txt");
File.Copy(image.FileName, _view.LogoURL);
}
The Bug
when we try to update the same file it fired an error:
"because it is being used by another process.
Ex. if we upload pic1, everything is well, we try to change to pic2 great job.
but if we try to back the pic1 fired the error especially if it happens in the same seesion.

Copying files into newly created folder giving error "its being used by another process

I try to create a sub-application that copies the database to the user desired location. Although an error is popping up that my newly created folder is being used by another application (i havent used any stream readers).
The files are correct and the copy to the selected directory is totaly working , although the problem starts when i create the folder and after i try to use him.
//Snippet
string SourceFile1 = #"C:\Users\user\Documents\DLLTESTBASE.mdf";
string SourceFile2 = #"C:\Users\user\Documents\DLLTESTBASE_log.ldf";
string BackupDirectory = BackupLocation.SelectedPath + "\\" + BackupName;
if (!Directory.Exists(BackupDirectory)){
Directory.CreateDirectory(BackupDirectory);
}
else{
MessageBox.Show("A copy has been found :\n" + BackupDirectory , "Copy has been stoped!");
}
string targetPath1 = BackupDirectory + "\\DB.mdf";
string targetPath2 = BackupDirectory + "\\DB_log.ldf";
try{
System.IO.File.Copy(SourceFile1, targetPath1);
System.IO.File.Copy(SourceFile2, targetPath2);
MessageBox.Show("Copy has been successful.", "Completed!");
}
catch (Exception ex){
MessageBox.Show("An error has been occured."+ex,"Operation failed!");}
}
The result must be that the 2 files will be inside of the folder.
Sql Data Base File in use with Sql Service
Goto Services
Stop "Sql Server" Service
you can use this link stop-or-start-sql-server-service
If u dont want to stop service use this link
Also u can use Attaching-and-Detach DB PragmaticallyAttaching-and-Detach
Try the following line before you create the files:
File.SetAttribute(targetpath1, FileAttribute.Normal);
You will get an exception thrown if the files already exist.
You will need to either delete the files and then write to them or use overwrite parameter:
System.IO.File.Copy(sourcefile1, targetPath1, true);
Sorry for late responce, as it seem the problem was occuring beacause of a hidden compartment of my main application, the problem solved after restarting my computer and reappeared when i runned the main application so you were right guys that sql file-connection was running (although it wasnt visible).
Thank you everyone for the help ☺

How can i save files in folder within the IIS of outside of the Application folder in asp.net

In my web application, i have some files those are saving within application it's creating a folder for saving files but i need to save those file outside of the application and inside of IIS.how can i do this?
With in application Folder we are using below code
Server.MapPath(Path)
For Saving in IIS How can i Write?
Thank you
you need to create a virtual directory that points ti the folder outside.
Go to IIS right click on your website. click on Add Virtual directry from the menu.Give an alias for the directory select your desired folder and you are done. it will consider this outside folder as an internal folder and work the same way. check this link How to: Create and Configure Virtual Directories in IIS 7.0
Disclaimer: but you will have to do this after hosting to iis i.e publishing. while using visual studio in dev environment i.e debugging it will store in internal directories only
Edit: for creating virtual directories this is the code. I have not tested its validity.
static void CreateVDir(string metabasePath, string vDirName, string physicalPath)
{
// metabasePath is of the form "IIS://<servername>/<service>/<siteID>/Root[/<vdir>]"
// for example "IIS://localhost/W3SVC/1/Root"
// vDirName is of the form "<name>", for example, "MyNewVDir"
// physicalPath is of the form "<drive>:\<path>", for example,"C:\Inetpub\Wwwroot"
try
{
DirectoryEntry site = new DirectoryEntry(metabasePath);
string className = site.SchemaClassName.ToString();
if ((className.EndsWith("Server")) || (className.EndsWith("VirtualDir")))
{
DirectoryEntries vdirs = site.Children;
DirectoryEntry newVDir = vdirs.Add(vDirName, (className.Replace("Service", "VirtualDir")));
newVDir.Properties["Path"][0] = physicalPath;
newVDir.Properties["AccessScript"][0] = true;
// These properties are necessary for an application to be created.
newVDir.Properties["AppFriendlyName"][0] = vDirName;
newVDir.Properties["AppIsolated"][0] = "1";
newVDir.Properties["AppRoot"][0] = "/LM" + metabasePath.Substring(metabasePath.IndexOf("/", ("IIS://".Length)));
newVDir.CommitChanges();
}
else
}
catch (Exception ex)
{
}
}
Normally you can not create a folder outside the root path i.e. if you have your application in say C:\inetpub\testapp you can only create a folder inside testapp. This restriction is for security reason where a web server is not supposed to allow access to anything above root folder.
Moreover it's not recommended to write any folders/files in the root folder as writing to root folder cause appdomain to recycle after certain number of writes (default is 15) causing session loss. See my answer here.
However there is a workaround
Add a path of your server to web.config and then fetch it in your code.Use something like below in the appsettings section of web.config
<add key="logfilesPath" value="C:\inetpub\MyAppLogs" />
Create a folder of above path and add Users group to your folder and give that group full permission (read/write). (Adding permission is very important)
In your code you can fetch as below
string loggerPath = (ConfigurationManager.AppSettings["logfilesPath"]);
Hope this helps

Unable to load images in Visual Studio 2015

I am having an issue with using the ImageLocation of a pictureBox. I went to:
Documents\VisualStudios\Projects\Program Name:
Then I create a new folder called images and within that folder i put the pictures(rock.png , paper.png )I intend to use. Keep in mind I can not load from the C drive, I have to turn this project in, so that it can work on any computer. Am I loading my images in the wrong location? or Am i accessing them wrong?
if (PlayerOne == Rock && PlayerTwo == Scissors)
{
ScoreOne++;
picture1.ImageLocation = #"images\rock.png";
picture2.ImageLocation = #"images\paper.png";
lblOneScore.Text = Convert.ToString(ScoreOne);
lblShowWinner.Text = " Player One Wins! ";
picture1.Load();
picture2.Load();
}
Instead of setting the ImageLocation property, try:
picture1.Load(#"C:\temp\pic.jpg");
The picturebox load method also accepts URL's (if you can't access drives and it needs to work on any PC without hardcoded UNC paths):
picture1.Load("http://i.stack.imgur.com/FmIGn.png");
Or use the app's location if you have packaged it with an image:
picture1.Load(Application.StartupPath + "\\a.jpg");
Or use a Resource file:
I would love to use resourceFile but I can not find it on Visual Studios 2015 only for 2013 and previous versions
It hasn't changed from VS2013 to VS2015, in your Winforms project, expand the Project Properties and double click on Resources.resx, then add an image:
picture1.Image = global::ProjectName.Properties.Resources.ImageName;
VisualStudios/Projects/fileName/filename/bin/Debug/create images folder and insert pictures in that folder and my original code posted works just fine

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

Categories