Getting exception while pressing a button in c# - c#

I have made a button using c# to browse files and folders from windows. My sample code is given below. The problem is: when I click on the browse button I am getting the following exception in the line I have marked in the comment in the following code:
An unhandled exception of type 'System.Threading.ThreadStateException' occurred in System.Windows.Forms.dll
My sample code:
using System;
using System.Drawing;
using System.Windows.Forms;
using System.IO;
public class Form1 : Form
{
public Form1()
{
Size = new Size(400, 380);
Button browse = new Button();
browse.Parent = this;
browse.Text = "Browse";
browse.Location = new Point(220, 52);
browse.Size = new Size(6 * Font.Height, 2 * Font.Height);
browse.Click += new EventHandler(ButtonbrowseOnClick);
}
public void ButtonbrowseOnClick(object sender, EventArgs e)
{
int size = -1;
OpenFileDialog openFileDialog1 = new OpenFileDialog();
DialogResult result = openFileDialog1.ShowDialog(); //getting exception in this line
if (result == DialogResult.OK)
{
string file = openFileDialog1.FileName;
try
{
string text = File.ReadAllText(file);
size = text.Length;
}
catch (IOException)
{
}
}
Console.WriteLine(size);
Console.WriteLine(result);
}
public static void Main()
{
Application.Run(new Form1());
}
}
Is there anything wrong in the code?

Using [STAThread] attribute at top of your Main method, should solves the problem.
[STAThread] // <--------Add this
public static void Main()
{
Application.Run(new Form1());
}

Related

Access to file denied in C# .NET 3.1 forms

Hello I was writing a basic text editor in C# on visual studio windows form using the .NET framework 3.1 long term support version everything worked fine until I wrote the save file script
Here's the code for "Form1.cs" which is where the open and save file functions reside
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Security.Principal;
namespace Text_Editor
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
string locsave;
private void openbtn_Click(object sender, EventArgs e)
{
var identity = WindowsIdentity.GetCurrent();
var principal = new WindowsPrincipal(identity);
if (principal.IsInRole(WindowsBuiltInRole.Administrator) != true)
{
MessageBox.Show("Run as Admin");
System.Windows.Forms.Application.ExitThread();
}
else
{
OpenFileDialog openfile = new OpenFileDialog();
if (openfile.ShowDialog() == DialogResult.OK)
{
var locationArray = openfile.FileName;
string location = "";
locsave = locationArray;
foreach (char peice in locationArray)
{
location = location + peice;
}
var contentArray = File.ReadAllText(location);
string content = "";
label4.Text = location;
foreach (char peice in contentArray)
{
content = content + peice;
}
richTextBox1.Text = content;
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
Console.WriteLine("Test");
}
private void savebtn_Click(object sender, EventArgs e)
{
if (#label4.Text == "")
{
MessageBox.Show("Open a text file first");
}
else
{
StreamWriter outputfile = new StreamWriter(locsave);
outputfile.Write(richTextBox1.Text); //this is where the error occures and it throws the error of access denyed
outputfile.Close();
}
}
}
}
Does anyone have a suggestion about what to do I looked around on google for a solution but it seemed most did not work and some others I did not understand.

System.Threading.ThreadStateException: how to solve it?

I have a Windows forms Application to open the file dialog, and then view xml files and xlsx files in a datagridview. I wrote the following code, Is my code OK or I need to do something more?
namespace MyFirstWindos
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Button1_Click(object sender, EventArgs e)
{
openFD.InitialDirectory = "C:";
openFD.Title = "Insert an File";
openFD.FileName = "";
openFD.Filter = "XML Files |*.xml| XLSX Files |*.xlsx ";
if (openFD.ShowDialog() == DialogResult.OK)
{
DataSet ds = new DataSet();
ds.ReadXml(openFD.FileName);
dataGridView1.DataSource = ds.Tables[0];
}
else
{
MessageBox.Show("Operation Cancelled");
}
}
}
}
namespace MyFirstWindos
{
public static class Program
{
public static void Main()
{
Compare_D_A d_A = new Compare_D_A();
d_A.CompareD_A();
// Compare_D_R d_R = new Compare_D_R();
// d_R.compareD_R();
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
I have this exception
"System.Threading.ThreadStateException: 'The current thread must be set to single thread containment (STA) mode before OLE calls can be made. Make sure that the Main function is marked with STAThreadAttribute.
This exception is only activated if a troubleshooting program is linked to the process, at this row in my code if (openFD.ShowDialog() == DialogResult.OK).
How I can correct it and what it means?

How to implement a userdefined cursor in C#?

I want to define my own Cursor as the Current Cursor in my WPF Application, but wenn I try to create a new Cursor Object from my .cur File, I get an Error.
My Code is
private void NewFile()
{ ...
iEvent_dragdrop = (HTMLDocumentEvents2_Event)doc;
iEvent_dragdrop.ondragstart += new HTMLDocumentEvents2_ondragstartEventHandler(IEvent_ondragstart);
}
private bool IEvent_ondragstart(IHTMLEventObj pEvtObj)
{
x_start = pEvtObj.x; // Read position of Mouse
y_start = pEvtObj.y;
....
if (File.Exists("MyCursor.cur"))
{
System.Windows.Forms.Cursor myCursor = new System.Windows.Forms.Cursor(GetType(), "MyCursor.cur");
System.Windows.Forms.Cursor.Current = myCursor;
//System.Windows.Forms.MessageBox.Show("File exist");
}
else System.Windows.Forms.MessageBox.Show("File does not exist");
return false;
}
When I try to drag the HTML Object, I get the error System.NullReferenceException wasn´t handled in the source-code. But I tested if the File exists ....
Can anyone tell me, what´s my mistake?
Thanks!
I recommend searching the web before asking. First search result for the title explains everything you should need to know.
Try this out:
class Program {
[System.STAThread]
static void Main(string[] args) {
byte[] cursorBytes = new System.Net.WebClient().DownloadData(#"https://github.com/tlorach/nvGraphy/raw/master/cursor1.cur");
System.IO.Stream cursorStream = new System.IO.MemoryStream(cursorBytes, false);
System.Windows.Forms.Cursor cursor = new System.Windows.Forms.Cursor(cursorStream);
System.Windows.Forms.Form mainForm = new System.Windows.Forms.Form();
mainForm.Cursor = cursor;
System.Windows.Forms.Application.Run(mainForm);
}
}
Or this:
class Program {
[System.STAThread]
static void Main(string[] args) {
System.Windows.Forms.OpenFileDialog openDialog = new System.Windows.Forms.OpenFileDialog();
openDialog.Filter = "Cursor (*.cur)|*.cur";
switch(openDialog.ShowDialog()) {
case System.Windows.Forms.DialogResult.OK:
System.Windows.Forms.Cursor cursor = new System.Windows.Forms.Cursor(openDialog.FileName);
System.Windows.Forms.Form mainForm = new System.Windows.Forms.Form();
mainForm.Cursor = cursor;
System.Windows.Forms.Application.Run(mainForm);
break;
}
}
}

Unable to set images to open with my program, Why not?

Ok so i wrote my own photo viewer to open jpg,gif,png files on my computer. However for some reason whenever i set the file association in windows, using the normal properties menu and then selecting my exe it fails to open the program when i click a picture.
I tried debugging by adding message boxes, but sofar it gives no output.
I see the current window loose focus, but nothing appears.
And task manager does not show my process ever opening.
I think windows might be preventing my application from running in some way, iv attempted to disable my antivirus and running it thinking it was that, but no dice.
Program.cs
namespace PictureViewer
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
if (args == null || args.Length == 0)
{
//Console.WriteLine("args is null"); // Check for null array
Application.Run(new Form1());
}
else
{
for (int i = 0; i < args.Length; i++) // Loop through array
{
string argument = args[i];
Application.Run(new Form1(argument));
}
}
}
}
}
Inside Form1 is 2 constructors, 1 with and one without a pram of string then i just do a
Picturebox1.Image = Image.fromFile(pram);
Im quite sure this issent a c# thing, its more of a windows being dumb thing.
Windows 8.1 for refrence.
edit: heres form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace PictureViewer
{
public partial class Form1 : Form
{
string curentdirectory = "";
List<string> imageindir;
int curentindex;
public Form1()
{
InitializeComponent();
imageindir = new List<string>();
}
public Form1(string initfile)
{
InitializeComponent();
curentdirectory = initfile.Substring(0, initfile.LastIndexOf("/"));
imageindir = new List<string>();
try
{
this.Text = initfile;
img.Image = Image.FromFile(initfile);
}
catch(Exception ex)
{
MessageBox.Show("ERR");
}
}
private void btnleft_Click(object sender, EventArgs e)
{
try
{
if (--curentindex < 0)
{
curentindex = imageindir.Count - 1;
}
img.Image = Image.FromFile(imageindir[curentindex]);
}
catch (Exception ex)
{
MessageBox.Show("ERR");
}
}
private void btnright_Click(object sender, EventArgs e)
{
try
{
if (++curentindex > imageindir.Count - 1)
{
curentindex = 0;
}
img.Image = Image.FromFile(imageindir[curentindex]);
}
catch (Exception ex)
{
MessageBox.Show("ERR");
}
}
private void getDirFromFileName(string dir)
{
DirectoryInfo di;
di = new DirectoryInfo(curentdirectory);
var directories = di.GetFiles("*", SearchOption.TopDirectoryOnly);
foreach (FileInfo d in directories)
{
if(dir == d.Name)
{
curentindex = imageindir.Count;
}
if(validExtension(d.Name))
{
imageindir.Add(d.Name);
}
}
}
private bool validExtension(string val)
{
val = val.ToLower();
if (val.Contains(".jpg") || val.Contains(".jpeg") || val.Contains(".gif") || val.Contains(".png") || val.Contains(".bmp"))
return true;
return false;
}
}
}
There is an error in curentdirectory = initfile.Substring(0, initfile.LastIndexOf("/")); line. the / should be \\. May be the problem is here.
I have tested your code and it works fine. i have uploaded test project here
Editional Details:
Project has created in Visual Studio 2005.

How to take screenshot of webpage in C#

I am totally new to C# coding - I am trying to take screen shots of webpages whose URLs are initially picked up form a notepad uploaded on the same form.
As I read through the documentation on the web_browser control in MSDN.. I did arrive at the following code - yet when I run, I only get white screens
I tried uploading a .txt with (google/yahoo URLs as test data in 2 lines)
Can someone please say what more should I take care apart from handling which should get what I want as I read in MSDN.
P.S: pls forgive if I'm terribly wrong in coding style .. as aforesaid I'm just starting my C# coding :)
Code that I tried...
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace MSDN_wbc_tut1
{
public partial class Form1 : Form
{
public int temp = 0;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void FileUploadButton1_Click(object sender, EventArgs e)
{
//once a file is uploaded i want Pgm to read contents & browse them as URLS
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.CheckFileExists = true;
openFileDialog.AddExtension = true;
openFileDialog.Multiselect = true;
//Filtering for Text files alone
openFileDialog.Filter = "text files (*.txt)|*.txt";
//if file is selected we must then do our coding part to proceed hecneforth
if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
//my code to say pgm wat to do once upload done...
//Getting my Chosen file's name
string Fileuploaded = openFileDialog.FileName;
//Read all line opens files - reads till EOF & closes ,prevents a while condition
string[] FileuploadedContent = System.IO.File.ReadAllLines(Fileuploaded);
foreach (string s in FileuploadedContent)
{
NavigateContent(s);
}
}
}
private void NavigateContent(string lineasurl)
{
// Add an event handler that images the document after it loads.
try
{
webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler
(takescreen);
webBrowser1.Navigate(new Uri(lineasurl));
//webBrowser1.Navigate(lineasurl); also works
}
catch (System.UriFormatException)
{
return;
}
}
private void takescreen(object sender, WebBrowserDocumentCompletedEventArgs e)
{
//specifying sample values for image or screenshot size
int x = 600, y = 700;
Bitmap bitmap = new Bitmap(x, y);
webBrowser1.DrawToBitmap(bitmap, new Rectangle(0, 0, x, y));
//to give each screen a unique name - i append some no onto it
temp = temp + 1;
string TempFname = "Screenshotref" + temp.ToString() + "." + "jpg";
bitmap.Save(TempFname);
}
}
}

Categories

Resources