error : Value of 'null' is not valid for 'stream' - c#

I have opened Resources.resx file of a WinForms application project and copied images there. I am using the code shown below to get an image from the resources, but getting following error:
Value of 'null' is not valid for 'stream'.
The error occurs in this line:
btn.BackgroundImage = new Bitmap(
System.Reflection.Assembly.GetEntryAssembly().GetManifestResourceStream(test));
Relevant code:
private void genericButton_event(object sender, EventArgs e)
{
var btn = (Button)sender;
string test = "StudentModule.Properties.Resources" + btn.Name + ".png";
//Getting the error here:
btn.BackgroundImage = new Bitmap(System
.Reflection
.Assembly
.GetEntryAssembly()
.GetManifestResourceStream(test));
}
The value of test is "StudentModule.Properties.ResourcesbtnAbout.png", but I think it should be: "StudentModule.Properties.Resources.btnAbout.png". I tried this line also but it's not working:
string test = "StudentModule.Properties.Resources." + btn.Name + ".png";
What is the mistake I am doing here?

GetManifestResourceStream() returns null when the stream could not be found. Which will then bomb the Bitmap constructor.
So the string you used is wrong. It isn't clear exactly how you embedded the resource. Do strongly favor using the resource designer, Project + Resources tab. Click the arrow on the Add Resource button, choose "Add Existing File" and select the file. You can then use the ResourceManager to get the bitmap:
var imageName = "Chrysanthemum";
btn.BackgroundImage = (Bitmap)Properties.Resources.ResourceManager.GetObject(imageName);
Note how the resource name is just the plain resource name as it appears in the resource designer.

Related

C# project, problem how use files in project directory Resources

i did research about this, but nothing worked.
I created folder in my project in Visual Studio 2019 => Images and i placed a file footer.png here.
In Visual Studio => Right click on folder Images, added new item Resources and add this line => Name -> FooterBG and Value -> Images/footer.png
in code:
string pathToFooter = Resource.FooterBG;
in debug get return Images\footer.png
When i want to add this to string with html tags, dont work:
String htmlTags = "<table background='"+ pathToFooter + "'><tbody><tr><td></td></tr></tbody></table>";
Please any tips what im doing wrong ?
Based on my test, the pathToFooter is not the actual path of the image.
Here is a code example you can refer to:
private void button1_Click(object sender, EventArgs e)
{
string pathToFooter = Resource1.FooterBG;
string path = AppDomain.CurrentDomain.BaseDirectory + Path.Combine(#"../..", pathToFooter);
String htmlTags = "<table background='" + path + "' width='1000' height='800' align='center'><tbody><tr><td></td></tr></tbody></table>";
webBrowser1.DocumentText = htmlTags;
}
Result:

How can I pass a file/file path from one Button_Click event to another in C#?

I have a fileupload control (FileUpload1) in my webform which I use to load an excel file. I use a button called btn_open to display it in a gridview on click.
I also save the file using FileUpload1.SaveAs() method in a server folder.
Now I have another button called btn_edit which on click needs to use the same
file that I just loaded to do another set of operations.
How do I pass this file/file path from btn_open_Click to btn_edit_Click? I do not want to specify the exact location on the code. There will be multiple times I will open new excel files so I don't want to specify the file path to the server for every new file.This needs to happen programatically. Also, I want to avoid using Interop if its possible.
The following code snippet might make things more clear as to what I want to do.
protected void btn_open_Click(object sender, EventArgs e)
{
string fileExtension = System.IO.Path.GetExtension(FileUpload1.FileName);
if (fileExtension.ToLower() == ".xlsx" || fileExtension.ToLower() == ".xls")
{
string path = Path.GetFileName(FileUpload1.FileName); //capture the file name of the file I have uploaded
path = path.Replace(" ", ""); // if there is any spacing between the file name it will remove it
FileUpload1.SaveAs(Server.MapPath("~/ExcelFile/") + path); //saves to Server folder called ExcelFile
String ExcelPath = Server.MapPath("~/ExcelFile/") + path; // Returns the physical file path that corresponds to the specified virtual path.
.
.
*code to display it in gridview*
.
.
}
else
{
Console.Writeline("File type not permissible");
}
}
protected void btn_edit_Click(object sender, EventArgs e)
{
//HOW DO I PASS THE ABOVE FILE HERE PROGRAMATICALLY WITHOUT SPECIFYING IT'S EXACT LOCATION ON THE SERVER??
}
Using Session variable helped me solve my problem. Hopefully it will be helpful to other people who might encounter similar issue.
On the first button (in my case btn_open_Click), add:
Session["myXlsPath"] = ExcelFilePath;
Note: "myXlsPath" is just a name I created for my Session variable. ExcelFilePath is the path of my excel file that I want to pass to the other button.
On the button you want to pass the file path to (in my case btn_edit_Click), add:
string ExcelFilePath = (string)Session["myXlsPath"];

How to dynamicaly load and save user settings in WPF multi window application?

I'm trying to save user setting in a WPF application. I want to save their Window position and size. To do so, I inspire myself of this.
I change a little the save code to do the following :
var oBaseProp = Properties.Settings.Default.Properties["baseProp"];
Properties.Settings.Default["baseProp"] = "1";
System.Configuration.SettingsProperty property = new System.Configuration.SettingsProperty("W_" + this.GetType().FullName + "_PLACEMENT"
, typeof(string), oBaseProp.Provider, false, GetPlacement(this), System.Configuration.SettingsSerializeAs.String, oBaseProp.Attributes,
false, false);
Properties.Settings.Default.Properties.Add(property);
Properties.Settings.Default["W_" + this.GetType().FullName + "_PLACEMENT"] = GetPlacement(this);
Properties.Settings.Default.Save();
BaseProp is a string property defined in my settings which is useless and just used to retrieve provider and other things.
Everything works fine for saving, I have a new file in C:\Users\christophe.mom.DOMAINE-EPSILOG\AppData\Local\Epsilog\MSSante_GUI.vshost.exe_Url_fkwxpmo4exiyrjk2vha2qu2upx5sgrvn\1.0.0.0 path, user.config that contains the desired data.
The thing is, I cannot load this file as settings file :
void StandardWindow_SourceInitialized(object sender, EventArgs e)
{
try
{
Properties.Settings.Default.Reload();
var sPlacement = (string)Properties.Settings.Default.Properties["W_" + this.GetType().FullName + "_PLACEMENT"].DefaultValue;
if (!string.IsNullOrWhiteSpace(sPlacement))
{
this.SetPlacement(this, sPlacement);
}
}
catch { }
}
I don't understand why my actual settings are not loaded. I tried in execution (not debug) mode too, and still no results.
Is someone have an idea ?
Thanks !
Well, in fact, this works only on execution mode compiled in release (in my case).

Load Image from Embedded resource WP8 / C#

I am trying to load an image from an Embedded resource in a windows phone application
Here is my project setup:
Module1 = Phone Application
Module2 = ClassLibrary.dll
Module1 calls Module2 to create all of the data objects for the phone app.
When Module2 is creating the objects, I wanted to load an image from a resource.
The resource is "Default.png" and saved in the "Images" directory ( Build Action = Embedded Resource, Copy to Output Directory = Copy Always)
The code I am using produces an exception
ex = {"The request is not supported. "}
Here is the code:
private void LoadImage()
{
Assembly curAssembly = null;
curAssembly = Assembly.GetExecutingAssembly();
string [] names = curAssembly.GetManifestResourceNames();
// names[0] = "Storage.Images.Default.png"
// so I know I am using the correct name
Stream resStream = curAssembly.GetManifestResourceStream("Storage.Images.Default.png");
BitmapImage bitMapImage = new BitmapImage();
try
{
bitMapImage.SetSource(resStream);
}
catch (Exception ex)
{
Debug.WriteLine(ex.ToString());
}
}
Can you help a newbie out?
Thanks
Steps to get that working:
First Appraoch
Right-click on your project in VS and choose "Add New Item"
From "General" tab choose "Resources File"
Open that resource_file.resx which you just added to your project and choose "Add Existing Item" and then choose your image.
Then then in your LoadImage method, do this:
private void LoadImage()
{
Drawing.Bitmap bitMapImage = resource_file.name_of_your_image;
}
Note: In this code, I assumed that the name you choose for your resource file is "resource_file"
Second Approach
System.Resources.ResourceManager rm = new System.Resources.ResourceManager(this.GetType().Assembly.GetName().Name + ".resource_file", this.GetType().Assembly);
System.Drawing.Bitmap bmp= (System.Drawing.Bitmap)rm.GetObject("Baba");
or use can use System.Resources.ResourceReader and other approaches
Figured it out...
The name I was using to load the resource was wrong...
Using the name from the array returned in this call
string [] names = curAssembly.GetManifestResourceNames();
And it works flawlessly

A problem with Relative Path Resolution when setting an Image Source

I have built a small WPF application that allows users to upload documents and then select one to display.
The following is the code for the file copy.
public static void MoveFile( string directory, string subdirectory)
{
var open = new OpenFileDialog {Multiselect = false, Filter = "AllFiles|*.*"};
var newLocation = CreateNewDirectory( directory, subdirectory, open.FileName);
if ((bool) open.ShowDialog())
CopyFile(open.FileName, newLocation);
else
"You must select a file to upload".Show();
}
private static void CopyFile( string oldPath, string newPath)
{
if(!File.Exists(newPath))
File.Copy(oldPath, newPath);
else
string.Format("The file {0} already exists in the current directory.", Path.GetFileName(newPath)).Show();
}
The file is copied without incident. However, when the user tries to select a file they just copied to display, A file not found exception. After debugging, I've found that the UriSource for the dynamic image is resolving the relative path 'Files{selected file}' to the directory that was just browsed by the file select in the above code instead of the Application directory as it seems like it should.
This problem only occurs when a newly copied file is selected. If you restart the application and select the new file it works fine.
Here's the code that dynamically sets the Image source:
//Cover = XAML Image
Cover.Source(string.Format(#"Files\{0}\{1}", item.ItemID, item.CoverImage), "carton.ico");
...
public static void Source( this Image image, string filePath, string alternateFilePath)
{
try
{image.Source = GetSource(filePath);}
catch(Exception)
{image.Source = GetSource(alternateFilePath);}
}
private static BitmapImage GetSource(string filePath)
{
var source = new BitmapImage();
source.BeginInit();
source.UriSource = new Uri( filePath, UriKind.Relative);
//Without this option, the image never finishes loading if you change the source dynamically.
source.CacheOption = BitmapCacheOption.OnLoad;
source.EndInit();
return source;
}
I'm stumped. Any thought's would be appreciated.
Although I don't have a direct answer, you should use caution for such allowing people to upload files. I was at a seminar where they had good vs bad hackers to simulate real life exploits. One was such that files were allowed to be uploaded. They uploaded malicious asp.net files and called the files directly as they new where the images were ultimately presented to the users, and were able to eventually take over a system. You may want to verify somehow what TYPES of files are being allowed and maybe have stored in a non-exeucting directory of your web server.
It turns out I was missing an option in the constructor of my openfiledialogue. The dialogue was changing the current directory which was causing the relative paths to resolve incorrectly.
If you replace the open file with the following:
var open = new OpenFileDialog{ Multiselect = true, Filter = "AllFiles|*.*", RestoreDirectory = true};
The issue is resolved.

Categories