How to solve the problem in c#

Kailash Sahu 141 Reputation points
2021-09-11T13:23:43.247+00:00

Getting a error, How to solve the problem131204-op.jpg

        public static bool CompileCSharpCode(string sourceFile, string exeFile)  
		{  
			string str = @"D:\Test";  
  
			CodeDomProvider codeDomProvider = CodeDomProvider.CreateProvider("CSharp");  
			CompilerParameters compilerParameters = new CompilerParameters();  
			compilerParameters.ReferencedAssemblies.Add(".\\System.dll");  
			compilerParameters.ReferencedAssemblies.Add(".\\System.Data.dll");  
			compilerParameters.ReferencedAssemblies.Add(".\\System.Drawing.dll");  
			compilerParameters.ReferencedAssemblies.Add(".\\System.Windows.Forms.dll");  
			compilerParameters.ReferencedAssemblies.Add(".\\System.Design.dll");  
			compilerParameters.ReferencedAssemblies.Add(".\\ResourceManager.dll");  
			compilerParameters.CompilerOptions = "/t:winexe";  
			MessageBox.Show(compilerParameters.CompilerOptions);  
			DirectoryInfo directoryInfo = new DirectoryInfo(str + "\\selectedimages");  
			FileInfo[] files = directoryInfo.GetFiles();  
			compilerParameters.EmbeddedResources.Clear();  
			//compilerParameters.EmbeddedResources.Add(".\\first.png");  
			//compilerParameters.EmbeddedResources.Add(".\\next.png");  
			//compilerParameters.EmbeddedResources.Add(".\\prev.png");  
			//compilerParameters.EmbeddedResources.Add(".\\last.png");  
			//compilerParameters.EmbeddedResources.Add(".\\play.png");  
			//compilerParameters.EmbeddedResources.Add(".\\pause.png");  
			//compilerParameters.EmbeddedResources.Add(".\\save_file.jpg");  
			//compilerParameters.EmbeddedResources.Add(".\\ZoomIn.png");  
			//compilerParameters.EmbeddedResources.Add(".\\ZoomOut.png");  
			//compilerParameters.EmbeddedResources.Add(".\\1458172203_iPhoto.ico");  
			string[] array = new string[directoryInfo.GetFiles().Length];  
			int num = 0;  
			foreach (FileInfo fileInfo in files)  
			{  
				if (fileInfo.Extension.ToLower() == ".png" || fileInfo.Extension.ToLower() == ".jpg" || fileInfo.Extension.ToLower() == ".gif" || fileInfo.Extension.ToLower() == ".jpeg" || fileInfo.Extension.ToLower() == ".bmp" || fileInfo.Extension.ToLower() == ".tif")  
				{  
					array[num] = str + "\\selectedimages\\" + fileInfo.Name;  
					num++;  
				}  
			}  
			compilerParameters.EmbeddedResources.AddRange(array);  
			string[] fileNames = new string[]  
			{  
				".\\ImageBind.cs",  
				".\\ImageBind.Designer.cs",  
				".\\Class1.cs"  
			};  
			compilerParameters.GenerateExecutable = true;  
			compilerParameters.OutputAssembly = exeFile;  
			compilerParameters.GenerateInMemory = false;  
			CompilerResults compilerResults = codeDomProvider.CompileAssemblyFromFile(compilerParameters, fileNames);  
			if (compilerResults.Errors.Count > 0)  
			{  
				foreach (object obj in compilerResults.Errors)  
				{  
					CompilerError compilerError = (CompilerError)obj;  
					MessageBox.Show(compilerError.ToString());  
				}  
			}  
			return compilerResults.Errors.Count <= 0;  
		}  

Here is Form Code !

        private void button3_Click(object sender, EventArgs e)  
        {  
			string str = @"D:\Test";  
			try  
			{  
				if (this.imageListView1.SelectedItems.Count > 0)  
				{  
					if (!Directory.Exists(str + "\\selectedimages"))  
					{  
						Directory.CreateDirectory(str + "\\selectedimages");  
					}  
					string[] files = Directory.GetFiles(str + "\\selectedimages");  
					foreach (string text in files)  
					{  
						string text2 = text.ToString();  
						if (System.IO.File.Exists(text2))  
						{  
							System.IO.File.Delete(text2);  
						}  
					}  
					ResizeOpts resizeOpts = new ResizeOpts();  
					resizeOpts.ShowDialog(this);  
				int percentage = IResizer.Percentage;  
					if (percentage != 0)  
					{  
						IResizer resizer = new IResizer();  
						this.progressBar2.Minimum = 1;  
						this.progressBar2.Maximum = this.imageListView1.SelectedItems.Count;  
						Rectangle clientRectangle = this.progressBar2.Parent.ClientRectangle;  
						this.progressBar2.Left = (clientRectangle.Width - this.progressBar2.Width) / 2;  
						this.progressBar2.Top = (clientRectangle.Height - this.progressBar2.Height) / 2;  
						this.progressBar2.Step = 1;  
						this.saveFileDialog1.Title = "Save EXE File";  
						this.saveFileDialog1.CheckPathExists = true;  
						this.saveFileDialog1.DefaultExt = "exe";  
						this.saveFileDialog1.Filter = "EXE Files (*.exe)|*.exe|All Files (*.*)|*.*";  
						this.saveFileDialog1.FilterIndex = 1;  
						this.saveFileDialog1.RestoreDirectory = true;   
						if (this.saveFileDialog1.ShowDialog() == DialogResult.OK)  
						{  
							string fileName = this.saveFileDialog1.FileName;  
							//base.Enabled = false;  
							//this.panel2.Visible = false;  
							//this.imageListView1.Visible = false;  
							this.progressBar2.Visible = true;  
							for (int j = 0; j < this.imageListView1.SelectedItems.Count; j++)  
							{  
								string text3 = string.Concat(new object[]  
								{  
							"Processing Photo ",  
							this.progressBar2.Value,  
							" From ",  
							this.progressBar2.Maximum  
								});  
								using (Graphics graphics = this.progressBar2.CreateGraphics())  
								{  
									graphics.DrawString(text3, SystemFonts.DefaultFont, Brushes.Black, new PointF((float)(this.progressBar2.Width / 2) - graphics.MeasureString(text3.ToString(), SystemFonts.DefaultFont).Width / 2f, (float)(this.progressBar2.Height - 15)));  
								}  
								string text2 = Path.GetFileName(this.imageListView1.SelectedItems[j].FileName);  
								string fileName2 = this.imageListView1.SelectedItems[j].FileName;  
								string target = str + "\\selectedimages\\" + text2;  
								Image image = Image.FromFile(fileName2);  
								resizer.MaxX = image.Height * percentage / 100;  
								resizer.MaxY = image.Width * percentage / 100;  
								resizer.Resize(fileName2, target);  
								image.Dispose();  
								this.progressBar2.PerformStep();  
							}  
							this.progressBar2.Visible = false;  
							string directoryName = Path.GetDirectoryName(fileName);  
							string path = @"D:\Test\ResourceManager.dll";  
							//MessageBox.Show(path);  
							if (CompileCSharpCode(@"D:\Test\Class1.cs", fileName))  
							{  
								if (!System.IO.File.Exists(path))  
								{  
									System.IO.File.Copy(path, directoryName + "\\ResourceManager.dll");  
								}  
								MessageBox.Show("All Photos are Locked in Exe File");  
							}  
						//	base.Enabled = true;  
						}  
					}  
				}  
			}  
			catch (Exception ex)  
			{  
				MessageBox.Show("Error Generating EXE File : " + ex.ToString() + " Please Try again");  
			}  
		}  

IResizer.cs File

            using System;  
            using System.Collections.Generic;  
            using System.Linq;  
            using System.Text;  
            using System.Drawing;  
            using System.Windows.Forms;  
            using System.Drawing.Imaging;  

           namespace test1  
             {  
          public class IResizer  
            {  
          // public static ImageList selectedimages;  
            public static int Percentage;  
            public static int dpi;  
        /// <summary>  
       /// Maximum width of resized image.  
      /// </summary>  
       public  int MaxX { get; set; }  

       /// <summary>  
       /// Maximum height of resized image.  
        /// </summary>  
       public  int MaxY { get; set; }  

     /// <summary>  
    /// If true, resized image is trimmed to exactly fit  
    /// maximum width and height dimensions.  
    /// </summary>  
    public bool TrimImage { get; set; }  

    /// <summary>  
    /// Format used to save resized image.  
    /// </summary>  
    public ImageFormat SaveFormat { get; set; }  

    /// <summary>  
    /// Constructor.  
    /// </summary>  
    public IResizer()  
    {  
        MaxX = MaxY = 150;  
        TrimImage = false;  
        SaveFormat = ImageFormat.Jpeg;  
    }  

    /// <summary>  
    /// Resizes the image from the source file according to the  
    /// current settings and saves the result to the targe file.  
    /// </summary>  
    /// <param name="source">Path containing image to resize</param>  
    /// <param name="target">Path to save resized image</param>  
    /// <returns>True if successful, false otherwise.</returns>  
    public bool Resize(string source, string target)  
    {  
        using (Image src = Image.FromFile(source,true))  
        {  
            // Check that we have an image  
            if (src != null)  
            {  
                int origX, origY, newX, newY;  
                int trimX = 0, trimY = 0;  

                // Default to size of source image  
                newX = origX = src.Width;  
                newY = origY = src.Height;  

                // Does image exceed maximum dimensions?  
                if (origX > MaxX || origY > MaxY)  
                {  
                    // Need to resize image  
                    if (TrimImage)  
                    {  
                        // Trim to exactly fit maximum dimensions  
                        double factor = Math.Max((double)MaxX / (double)origX,  
                            (double)MaxY / (double)origY);  
                        newX = (int)Math.Ceiling((double)origX * factor);  
                        newY = (int)Math.Ceiling((double)origY * factor);  
                        trimX = newX - MaxX;  
                        trimY = newY - MaxY;  
                    }  
                    else  
                    {  
                        // Resize (no trim) to keep within maximum dimensions  
                        double factor = Math.Min((double)MaxX / (double)origX,  
                            (double)MaxY / (double)origY);  
                        newX = (int)Math.Ceiling((double)origX * factor);  
                        newY = (int)Math.Ceiling((double)origY * factor);  
                    }  
                }  

                // Create destination image  
                using (Bitmap  dest = new Bitmap(newX - trimX, newY - trimY))  
                {  
                    Graphics graph = Graphics.FromImage(dest);                                            
                    graph.InterpolationMode =  
                        System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;  
                    graph.DrawImage(src, -(trimX / 2), -(trimY / 2), newX, newY);  
                    dest.SetResolution(dpi, dpi);  
                    dest.Save(target, SaveFormat);  
                    graph.Dispose();  
                    dest.Dispose();  
                    // Indicate success  
                    return true;  
                }  
            }  
        }  
        // Indicate failure  
        return false;  
    }  
}  

}

Class1.cs File

using System;  
using System.Collections.Generic;  
//using System.Linq;  
using System.Text;  
using System.Windows.Forms;  
  
namespace test1  
{  
    class Class1  
    {  
       // public static string[] imagename;  
        [STAThread]  
        public static void Main()  
        {  
            Application.EnableVisualStyles();  
            Application.SetCompatibleTextRenderingDefault(false);  
            Application.Run(new ImageBind());  
        }  
    }  
      
}  

Resourcer.cs File

using System;  
using System.Drawing;  
using System.IO;  
using System.Reflection;  
using System.Windows.Forms;  
  
namespace test1  
{  
	// Token: 0x02000006 RID: 6  
	public class Resourcer  
	{  
		// Token: 0x06000042 RID: 66 RVA: 0x00004AFC File Offset: 0x00002CFC  
		public Resourcer(string containerFile)  
		{  
			if (!File.Exists(containerFile))  
			{  
				throw new Exception("Specified file does not exist");  
			}  
			this.asm = Assembly.LoadFrom(containerFile);  
		}  
  
		// Token: 0x06000043 RID: 67 RVA: 0x00004B34 File Offset: 0x00002D34  
		public Resourcer(LoadMethod loadmethod)  
		{  
			if (loadmethod == LoadMethod.FromCurrentCode)  
			{  
				this.asm = Assembly.GetExecutingAssembly();  
			}  
			else  
			{  
				this.asm = Assembly.GetCallingAssembly();  
			}  
		}  
  
		// Token: 0x06000044 RID: 68 RVA: 0x00004B6D File Offset: 0x00002D6D  
		public Resourcer(Type containedClass)  
		{  
			this.asm = Assembly.GetAssembly(containedClass);  
		}  
  
		// Token: 0x06000045 RID: 69 RVA: 0x00004B84 File Offset: 0x00002D84  
		public Image[] LoadImage()  
		{  
			ImageList imageList = new ImageList();  
			int num = 0;  
			int num2 = this.asm.GetManifestResourceNames().Length;  
			Resourcer.imagenames = new string[num2];  
			Image[] array = new Image[num2];  
			foreach (string text in this.asm.GetManifestResourceNames())  
			{  
				Stream manifestResourceStream = this.asm.GetManifestResourceStream(text);  
				array[num] = Image.FromStream(manifestResourceStream, true);  
				Resourcer.imagenames[num] = text;  
				num++;  
			}  
			return array;  
		}  
  
		// Token: 0x06000046 RID: 70 RVA: 0x00004C18 File Offset: 0x00002E18  
		public Image GetImageFromStream(string imgname)  
		{  
			string resourceFullName = this.GetResourceFullName(imgname);  
			if (resourceFullName == null)  
			{  
				throw new Exception("Can not find " + imgname + " resource in container file");  
			}  
			Stream manifestResourceStream = this.asm.GetManifestResourceStream(imgname);  
			return Image.FromStream(manifestResourceStream);  
		}  
  
		// Token: 0x06000047 RID: 71 RVA: 0x00004C6C File Offset: 0x00002E6C  
		public Stream GetResourceStream(string resourceFileName)  
		{  
			string resourceFullName = this.GetResourceFullName(resourceFileName);  
			if (resourceFullName == null)  
			{  
				throw new Exception("Can not find " + resourceFileName + "resource in container file");  
			}  
			return this.asm.GetManifestResourceStream(resourceFullName);  
		}  
  
		// Token: 0x06000048 RID: 72 RVA: 0x00004CB4 File Offset: 0x00002EB4  
		public string GetResourceFullName(string resName)  
		{  
			string result = null;  
			foreach (string text in this.asm.GetManifestResourceNames())  
			{  
				if (text.EndsWith(resName))  
				{  
					result = text;  
					break;  
				}  
			}  
			return result;  
		}  
  
		// Token: 0x06000049 RID: 73 RVA: 0x00004D0C File Offset: 0x00002F0C  
		public int GetResourcLength()  
		{  
			return this.asm.GetManifestResourceNames().Length;  
		}  
  
		// Token: 0x0400002C RID: 44  
		private Assembly asm;  
  
		// Token: 0x0400002D RID: 45  
		public static string[] imagenames;  
	}  
}  

Blockquote

Developer technologies | C#
Developer technologies | C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
0 comments No comments
{count} votes

Answer accepted by question author
  1. P a u l 10,761 Reputation points
    2021-09-11T14:34:12.673+00:00

    Try setting the "Copy to Output Directory" property to "Copy if newer" and "Build Action" to "None" for these files you're referencing here:

    string[] fileNames = new string[]
    {
        ".\\ImageBind.cs",
        ".\\ImageBind.Designer.cs",
        ".\\Class1.cs"
    };
    

    It looks like the compiler can't find these files from inside your bin folder where your app is ran from.


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.