I have a project that is not running anymore. I keep getting an error dialog that says "This application cannot be started. Do you want to view more information about this issue?". Also in the console, it says "The program '[10068] BinaryConverter.exe' has exited with code 0 (0x0)." Someone told me to uncheck the "Prefer 32-bit" option. When I do that, although the error dialog box is gone, the console still displays The program '[10068] BinaryConverter.exe' has exited with code 0 (0x0)." I cannot open the wpf app.
EDIT: By the way, the release folder is empty. When the app was working, my release folder had some things in it.
public MainWindow()
{
InitializeComponent();
}
public void readstuff (){
}
public static string getBetween(string strSource, string strStart, string strEnd)
{
int Start, End;
if (strSource.Contains(strStart) && strSource.Contains(strEnd))
{
Start = strSource.IndexOf(strStart, 0) + strStart.Length;
End = strSource.IndexOf(strEnd, Start);
return strSource.Substring(Start, End - Start);
}
else
{
return "";
}
}
private void BrowseButton2(object sender, RoutedEventArgs e)
{
OpenFileDialog fd = new OpenFileDialog();
fd.InitialDirectory = "\\\\folder1\\savelocation";
fd.Filter = "Binary Files | *.bin";
fd.ShowDialog();
filePath2.Text = fd.FileName;
}
private void SavingPathButton2(object sender, RoutedEventArgs e)
{
FolderSelectDialog fs = new FolderSelectDialog();
fs.InitialDirectory = "\\\\Nx3200\\supplier\\FONEX\\LambdaGain";
fs.ShowDialog();
savingPath2.Text = fs.FileName;
}
private void StartConversion2(object sender, RoutedEventArgs e)
{
try
{
Byte [] a1 = File.ReadAllBytes(filePath2.Text);
Byte[] a2 = new Byte[2 * (a1.Length)];
int i = 0;
while(i < a1.Length) {
a2[2*i] = a1[i];
a2[(2 * i) + 1] = 0;
i++;
}
try
{
string fullPath = Path.Combine(savingPath2.Text, "new");
File.WriteAllBytes(savingPath2.Text, a2);
MessageBox.Show("Conversion Complete");
} catch (UnauthorizedAccessException ex)
{
Form3 frm3 = new Form3();
frm3.Text = "X-Formatter";
frm3.ShowDialog();
}
}
catch (FileNotFoundException ex)
{
string stackTrace = ex.ToString();
Form1 frm1 = new Form1(stackTrace);
frm1.Text = "X-Formatter";
frm1.ShowDialog();
}
}
private void BrowseButton1(object sender, RoutedEventArgs e)
{
OpenFileDialog fd = new OpenFileDialog();
fd.InitialDirectory = "\\\\folder1\\savelocation";
fd.Filter = "Binary Files | *.bin";
fd.ShowDialog();
filePath1.Text = fd.FileName;
}
private void SavingPathButton1(object sender, RoutedEventArgs e)
{
FolderSelectDialog fs = new FolderSelectDialog();
fs.InitialDirectory = "\\\\folder1\\savelocation";
fs.ShowDialog();
savingPath1.Text = fs.FileName;
}
private void StartConversion1(object sender, RoutedEventArgs e)
{
try
{
Byte[] a1 = File.ReadAllBytes(filePath1.Text);
Byte[] a2 = new Byte[(a1.Length) / 2];
a2[0] = a1[0];
int i = 2;
int j = 1;
while (i < a1.Length)
{
a2[j] = a1[i];
i = i + 2;
j += 1;
}
try
{
File.WriteAllBytes(savingPath1.Text, a2);
MessageBox.Show("Conversion Complete");
}
catch (UnauthorizedAccessException ex)
{
Form3 frm3 = new Form3();
frm3.Text = "XGIGA formatter";
frm3.ShowDialog();
}
} catch(FileNotFoundException ex)
{
string stackTrace = ex.ToString();
Form1 frm1 = new Form1(stackTrace);
frm1.Text = "XGIGA Formatter";
frm1.ShowDialog();
}
}
private void FilePath1_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e)
{
}
private void Button_Click(object sender, RoutedEventArgs e)
{
AboutBox1 ab = new AboutBox1();
ab.Text = "XGIGA Formatter";
ab.ShowDialog();
}
}
Related
I am currently working on a file copying facility that allows me to select a source and a destination for the folders to be copied from and to. A progress bar is displayed after the user clicks on Copy.
The only issue is that All of my functions reside in one file which is form1.cs (as follows)
namespace CopyFacility
{
public partial class Form1 : Form
{
BackgroundWorker background = new BackgroundWorker();
FolderBrowserDialog folderBrowser = new FolderBrowserDialog();
OpenFileDialog openFile = new OpenFileDialog();
public Form1()
{
InitializeComponent();
background.WorkerSupportsCancellation = true;
background.WorkerReportsProgress = true;
background.DoWork += Background_DoWork;
background.RunWorkerCompleted += Background_RunWorkerCompleted;
background.ProgressChanged += Background_ProgressChanged;
}
string inputFile = null;
string outputFile = null;
private void CopyFile(string source, string destination, DoWorkEventArgs e)
{
FileStream fsOut = new FileStream(destination, FileMode.Create);
FileStream fsIn = new FileStream(source, FileMode.Open);
byte[] buffer = new byte[1048756];
int readBytes;
while((readBytes = fsIn.Read(buffer,0,buffer.Length)) > 0)
{
if(background.CancellationPending)
{
e.Cancel = true;
background.ReportProgress(0);
fsIn.Close();
fsOut.Close();
return;
}
else
{
fsOut.Write(buffer, 0, readBytes);
background.ReportProgress((int) (fsIn.Position * 100 / fsIn.Length));
}
fsOut.Write(buffer, 0, readBytes);
background.ReportProgress((int)(fsIn.Position * 100 / fsIn.Length));
}
fsIn.Close();
fsOut.Close();
}
private void Background_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
fileProgressBar.Value = e.ProgressPercentage;
}
private void Background_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if(e.Cancelled)
{
fileProgressBar.Visible = true;
lblMessage.Visible = true;
lblMessage.Text = "The process has been cancelled";
}
else
{
fileProgressBar.Visible = true;
lblMessage.Visible = true;
lblMessage.Text = "The process has been completed";
}
}
private void Background_DoWork(object sender, DoWorkEventArgs e)
{
CopyFile(inputFile, outputFile + #"\" + Path.GetFileName(inputFile),e);
}
private void btnCancel_Click(object sender, EventArgs e)
{
background.CancelAsync();
}
private void btnCopy_Click(object sender, EventArgs e)
{
if(background.IsBusy)
{
lblProgress.Visible = true;
}
else
{
fileProgressBar.Visible = true;
background.RunWorkerAsync();
}
}
private void btnSource_Click(object sender, EventArgs e)
{
if(openFile.ShowDialog() == DialogResult.OK )
{
inputFile = openFile.FileName;
btnSource.Text = inputFile;
}
}
private void btnDestination_Click(object sender, EventArgs e)
{
if (folderBrowser.ShowDialog() == DialogResult.OK)
{
outputFile = folderBrowser.SelectedPath;
btnDestination.Text = outputFile + #"\" + Path.GetFileName(inputFile);
}
}
}
}
I was wondering how I could go about putting the function "CopyFile" into it's own class that can be called whenever the button is clicked?
When I try creating a new class method and inserting the functions related to the copying function into a new class "CopyFunction.cs" , I get a following error from the code "InitializingComponent();" as follows
public CopyPresenter(BackgroundWorker background, FolderBrowserDialog folderBrwoser, OpenFileDialog openFile)
{
InitializeComponent();
background.WorkerSupportsCancellation = true;
background.WorkerReportsProgress = true;
background.DoWork += Background_DoWork;
background.RunWorkerCompleted += Background_RunWorkerCompleted;
background.ProgressChanged += Background_ProgressChanged;
}
The error says that the "InitializeComponent" doesn't exist in the current context.
private void comboBox9_SelectedIndexChanged(object sender, EventArgs e)
{
finish_day = Convert.ToInt32(comboBox9.Text);
}
private void comboBox10_SelectedIndexChanged(object sender, EventArgs e)
{
finish_month = Convert.ToInt32(comboBox10.Text);
}
private void comboBox11_SelectedIndexChanged(object sender, EventArgs e)
{
finfish_year = Convert.ToInt32(comboBox11.Text);
}
private void comboBox6_SelectedIndexChanged(object sender, EventArgs e)
{
begin_year = Convert.ToInt32(comboBox6.Text);
}
private void comboBox7_SelectedIndexChanged(object sender, EventArgs e)
{
begin_month = Convert.ToInt32(comboBox7.Text);
}
private void comboBox8_SelectedIndexChanged(object sender, EventArgs e)
{
begin_day = Convert.ToInt32(comboBox8.Text);
}
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
Thread.Sleep(1000); // important
from_bs_2 += serialPort1.ReadExisting();
Thread.Sleep(1000);
this.Invoke(new EventHandler(showdata));
Thread.Sleep(1000);
}
private void showdata(object sender, EventArgs e)
{
int changdu = from_bs_2.Length;
if (changdu > 50)
{
chushihua++;
string fro;
string[] parm = new string[6];
textBox1.Text += from_bs_2;
fro = from_bs_2;
parm = fro.Split('\n');
string path = "C:\\Users\\COM\\Desktop\\data_logging.txt";
FileStream fs = new FileStream(path, FileMode.Append, FileAccess.Write);
StreamWriter sw = new StreamWriter(fs);
for (int a = 0; a < 4; a++)
{
string[] zhongjian = new string[23];
zhongjian = parm[a].Split(';');
// textBox1.Text += zhongjian;
for (int keai = 0; keai < 23; keai++)
{
current[a, keai] = Convert.ToDouble(zhongjian[keai]);
sw.Write(current[a, keai]); sw.Write(';');
}
sw.WriteLine('/');
}
string[] zhongjian_2 = new string[23];
zhongjian_2 = parm[5].Split(';');
for (int m = 0; m < 23; m++) //
{
volatge[m] = Convert.ToDouble(zhongjian_2[m]);
sw.Write(volatge[m]); sw.Write(';');
}
sw.WriteLine('/');
DateTime dt = DateTime.Now; //strong text
int y = dt.Year; //
int yue = dt.Month; //
int d = dt.Day; //
int h = dt.Hour; //
int n = dt.Minute; //
textBox1.Text += y;
textBox1.Text += "-";
textBox1.Text += yue;
textBox1.Text += "-";
textBox1.Text += d;
textBox1.Text += "-";
textBox1.Text += h;
textBox1.Text += ":";
textBox1.Text += n;
textBox1.Text += "-";
textBox1.Text += "data logging times";
textBox1.Text += chushihua;
sw.Write(y); sw.Write("-"); sw.Write(yue); sw.Write("-"); sw.Write(d);
sw.Write("-"); sw.Write(h); sw.Write(":"); sw.Write(n); sw.WriteLine('/');
sw.Close();
fs.Close();
//////////////////time/////////////////////////////
string info = "INSERT INTO Logging_Data_2 (Time,Number,Power1,Power2,Power3,Power4,Power5,Power6,Power7,Power8,Power9,Power10,Power11,Power,Power12,Power13,Power14,Power15,Power16,Power17,Power18,Power19,Power20,Power21,Power22,Power23) values ('a',1,current[0, 0],current[0, 1],current[0, 2],current[0, 3],current[0, 4],current[0, 5],current[0, 6],current[0, 7],current[0, 8],current[0, 9],current[0, 10],current[0, 11],current[0, 12],current[0, 13],current[0, 14],current[0, 15],current[0, 16],current[0, 17],current[0, 18],current[0, 19],current[0, 20],current[0, 21],current[0, 22])";
using (System.Data.SQLite.SQLiteConnection connection = new System.Data.SQLite.SQLiteConnection("data source=logging_data.db"))
{
// connection.Open();
// using (DbTransaction transaction = connection.BeginTransaction())
// {
using (System.Data.SQLite.SQLiteCommand command = new System.Data.SQLite.SQLiteCommand(connection))
{
connection.Open();
command.CommandText = info;
//*emphasized text*command.ExecuteNonQuery();
}
// transaction.Commit();
// }
}
from_bs_2 = "";
if (textBox1.Text.Length > 1500)
{
textBox1.Text = "";
}
}
}
I am wirting a super simple file, get the data from arduino though serial ports, and than if i get data, first i log them in a txt file, and then I need to send them into a database for future calculation. therefore I installed the SQLite, and write caode in this, but when i test it, I can log data to txt fime, but nothing in my database.
I set up a database named logging_data, and the table is Logging_data_2, when I find I cant log any data to database, i just let the time be 'a', number be 1,but it still doesnt work. ask for help, thankyou!
I'm writing a Chat Program in C# (Windows Forms Application), the solution contains to projects which both consist of one form ( see picture ). While sending messages to each other works, I'm trying to record the conversation session in a .txt file named dateTime.txt using StreamWriter. Creating the file if it does not exist yet works, but whenever I open the text file, it only contains the last string that was written to it instead of containing the whole "conversation".
Does anybody know how to fix this?
This is the code of one of the forms, but since the forms do exactly the same, the code is the same too so i'm only posting the code of one Form. Would be great if somebody knows what I have to change so the whole conversation is recorded in the text file.
namespace Assignment3Client
{
public partial class Chat : Form
{
NamedPipeClientStream clientPipe = new NamedPipeClientStream("pipe2");
NamedPipeServerStream serverPipe = new NamedPipeServerStream("pipe1");
string msg = String.Empty;
string msgStr;
string name;
byte[] ClientByte;
public Chat()
{
InitializeComponent();
}
private void btnStartChat_Click(object sender, EventArgs e)
{
this.Text = "Waiting for a connection....";
if (txtBoxName.Text.Length == 0)
{
MessageBox.Show("please enter a name first.");
}
else
{
name = txtBoxName.Text;
clientPipe.Connect();
serverPipe.WaitForConnection();
if (serverPipe.IsConnected)
{
this.Text = "You are connected, " + name + "!";
btnStartChat.Enabled = false;
btnSend.Enabled = true;
txtBoxMsg.Enabled = true;
txtBoxMsg.Focus();
receiveWorker.RunWorkerAsync();
}
}
}
private void btnSend_Click(object sender, EventArgs e)
{
msg = "[" + name + ": " + DateTime.Now + "] " + txtBoxMsg.Text;
txtBoxChat.AppendText(msg + "\n");
FileWriter(msg);
sendWorker.RunWorkerAsync(msg); //start backgroundworker and parse msg string to the dowork method
txtBoxMsg.Clear();
txtBoxMsg.Focus();
}
private void sendWorker_DoWork(object sender, DoWorkEventArgs e)
{
Byte[] msgByte = System.Text.Encoding.GetEncoding("windows-1256").GetBytes(msg);
serverPipe.Write(msgByte, 0, msg.Length);
}
private void receiveWorker_DoWork(object sender, DoWorkEventArgs e)
{
ClientByte = new Byte[1000];
int i;
for (i = 0; i < ClientByte.Length; i++)
{
ClientByte[i] = 0x20;
}
clientPipe.Read(ClientByte, 0, ClientByte.Length);
msgStr = System.Text.Encoding.GetEncoding("windows-1256").GetString(ClientByte);
receiveWorker.ReportProgress(i, msgStr);
}
private void receiveWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
if ((string)e.UserState == String.Empty)
{ MessageBox.Show("no message"); }
else
{
string message = (string)e.UserState;
txtBoxChat.AppendText(message);
FileWriter(message);
txtBoxChat.BackColor = System.Drawing.Color.DarkBlue;
txtBoxChat.ForeColor = System.Drawing.Color.White;
}
}
private void receiveWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (clientPipe.IsConnected)
{
receiveWorker.RunWorkerAsync();
}
else
{
txtBoxMsg.Enabled = false;
btnSend.Enabled = false;
MessageBox.Show("Connection lost");
}
}
private void Chat_Activated(object sender, EventArgs e)
{
txtBoxChat.BackColor = new System.Drawing.Color();
txtBoxChat.ForeColor = new System.Drawing.Color();
}
private void exitMenuStrip_Click(object sender, EventArgs e)
{
this.Close();
}
private void conMenuSrip_Click(object sender, EventArgs e)
{
}
private void errMenuStrip_Click(object sender, EventArgs e)
{
}
public void FileWriter(string message)
{
string path = #"C:\Users\selin\Documents\TAFE\Term 3\dateTime.txt";
FileStream conLog;
if (!File.Exists(path))
{
conLog = new FileStream(path, FileMode.Create);
}
else
{
conLog = new FileStream(path, FileMode.Open);
}
StreamWriter writer = new StreamWriter(conLog);
writer.WriteLine(message);
writer.AutoFlush = true;
writer.Close();
MessageBox.Show("written to file" + message);
}
}
}
in FileWriter(string message) change
conLog = new FileStream(path, FileMode.Open);
to
conLog = new FileStream(path, FileMode.Append);
I am currently working on a small DB project in which I have tried implementing a browser for image so that they can be saved for each player accordingly.
I am particularly struggling with wring the path of the image to a string, and the storing that string into the arraylist which will then be used to load the file by using the path stored in that arraylist. As you see in the code I have tried to assign the OpenFd.FileName to a string called pathToImage but it doesn't work, the string remains empty after a quick debug check using MessageBox.Show(pathToImage)
Can anyone help me?
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.Collections;
using System.Text.RegularExpressions;
using System.Runtime.Serialization.Formatters.Binary;
namespace Assignment1_Template2
{
public partial class Form1 : Form
{
// =======================The data Structure ===========================
// ========Uses [SERIALIZABLE] to allow simple loading/saving ==========
[Serializable]
private struct myStruct
{ // The "constructor". Fills data structure with default values
public myStruct(int playerId)
{
uniquePlayerId = new int[playerId];
playerIgName = "";
contactStreet = "";
contactTown = "";
contactPostcode = "";
contactEmail = "";
contactTelephone = "";
imagePath = "";
for (int i = 0; i < playerId; ++i) uniquePlayerId[i] = 0;
}
// The data types of the struct
public int[] uniquePlayerId;
public string playerIgName;
public string contactStreet;
public string contactTown;
public string contactPostcode;
public string contactEmail;
public string contactTelephone;
public string imagePath;
}
// ================== End of data Structure definition ===================
// =======================================================================
// ================ Global Variables used in the Program =================
private ArrayList dataList; // This is the main data collection
private int currentEntryShown = 0; // current myStruct on display
private int numberOfEntries = 0; // total number of myStructs
private string filename = "C:\\test.dat"; // path of the file being read in
public string pathToImage = "";
public string pathToImagePlaceholder = "";
// =======================================================================
// ================== STARTING POINT FOR THE PROGRAM =====================
public Form1()
{
// Brings up the window.
InitializeComponent();
// Create the ArrayList
dataList = new ArrayList();
// Call methods implemented below
LoadData();
ShowData();
UpdatePrevNextBtnStatus();
}
// =========================================================================
// =================== END OF STARTING POINT FOR PROGRAM ===================
// ========= All further events are now triggered by user actions ==========
// =========================================================================
// =========================================================================
// ========================= BUTTON ACTION HANDLERS ========================
// =========================================================================
private void showPreviousBtn_Click(object sender, EventArgs e)
{
--currentEntryShown;
ShowData();
UpdatePrevNextBtnStatus();
}
private void showNextBtn_Click(object sender, EventArgs e)
{
++currentEntryShown;
if (currentEntryShown != dataList.Count)
{
ShowData();
}
UpdatePrevNextBtnStatus();
}
private void addNewPlayerBtn_Click(object sender, EventArgs e)
{
++numberOfEntries; // "Add" clicked: we need to create one more entry
currentEntryShown = numberOfEntries - 1; // scroll to an empty record at the end
// Create a new data structure, its constructor will fill it with default values
myStruct aNewStruct = new myStruct(5);
dataList.Add(aNewStruct); // add the frshly created struct to the ArrayList
ShowData(); // display
addNewPlayerBtn.Enabled = true; // can't do this again before saving
UpdatePrevNextBtnStatus();
}
private void SaveBtn_Click(object sender, EventArgs e)
{
SaveData(); // Call the Save() method implemented below
addNewPlayerBtn.Enabled = true; // After saving we can add another new record
UpdatePrevNextBtnStatus(); // Set 'Next' and 'Previous' button appearance
}
// =========================================================================
// =========================================================================
// ================ HANDLE DATA CHANGES BY USER ============================
// =========================================================================
// If the text box string is changed by the user, update
private void playerIdBox_TextChanged(object sender, EventArgs e)
{
myStruct aNewStruct = new myStruct(5);
aNewStruct = (myStruct)dataList[currentEntryShown];
aNewStruct.uniquePlayerId[0] = Convert.ToInt32(playerIdBox.Text);
dataList[currentEntryShown] = aNewStruct;
}
private void playerIgNameBox_TextChanged(object sender, EventArgs e)
{
myStruct aNewStruct = new myStruct(5);
aNewStruct = (myStruct)dataList[currentEntryShown];
aNewStruct.playerIgName = playerIgNameBox.Text;
dataList[currentEntryShown] = aNewStruct;
}
private void contactStreetBox_TextChanged(object sender, EventArgs e)
{
myStruct aNewStruct = new myStruct(5);
aNewStruct = (myStruct)dataList[currentEntryShown];
aNewStruct.contactStreet = contactStreetBox.Text;
dataList[currentEntryShown] = aNewStruct;
}
private void contactTownBox_TextChanged(object sender, EventArgs e)
{
myStruct aNewStruct = new myStruct(5);
aNewStruct = (myStruct)dataList[currentEntryShown];
aNewStruct.contactTown = contactTownBox.Text;
dataList[currentEntryShown] = aNewStruct;
}
private void contactPostcodeBox_TextChanged(object sender, EventArgs e)
{
myStruct aNewStruct = new myStruct(5);
aNewStruct = (myStruct)dataList[currentEntryShown];
aNewStruct.contactPostcode = contactPostcodeBox.Text;
dataList[currentEntryShown] = aNewStruct;
}
private void contactEmailBox_TextChanged(object sender, EventArgs e)
{
myStruct aNewStruct = new myStruct(5);
aNewStruct = (myStruct)dataList[currentEntryShown];
aNewStruct.contactEmail = contactEmailBox.Text;
dataList[currentEntryShown] = aNewStruct;
}
private void contactTelephoneBox_TextChanged(object sender, EventArgs e)
{
myStruct aNewStruct = new myStruct(5);
aNewStruct = (myStruct)dataList[currentEntryShown];
aNewStruct.contactTelephone = contactTelephoneBox.Text;
dataList[currentEntryShown] = aNewStruct;
}
// =========================================================================
// ================= HELPER METHODS FOR DISPLAYING DATA ====================
// =========================================================================
private void ShowData()
{
playerIdBox.Text = ((myStruct)dataList[currentEntryShown]).uniquePlayerId[0].ToString();
playerIgNameBox.Text = ((myStruct)dataList[currentEntryShown]).playerIgName;
contactStreetBox.Text = "" + ((myStruct)dataList[currentEntryShown]).contactStreet;
contactTownBox.Text = "" + ((myStruct)dataList[currentEntryShown]).contactTown;
contactPostcodeBox.Text = "" + ((myStruct)dataList[currentEntryShown]).contactPostcode;
contactEmailBox.Text = "" + ((myStruct)dataList[currentEntryShown]).contactEmail;
contactTelephoneBox.Text = "" + ((myStruct)dataList[currentEntryShown]).contactTelephone;
pathToImagePlaceholder = "" + ((myStruct)dataList[currentEntryShown]).imagePath;
MessageBox.Show(pathToImagePlaceholder);
try
{
playerPictureBox.Image = Image.FromFile(pathToImagePlaceholder);
}
catch
{
return;
}
}
private void UpdatePrevNextBtnStatus()
{
if (currentEntryShown > 0) showPreviousBtn.Enabled = true;
else showPreviousBtn.Enabled = false;
if (currentEntryShown < (numberOfEntries - 1)) showNextBtn.Enabled = true;
else showNextBtn.Enabled = false;
label1.Text = "Player ID";
label3.Text = (currentEntryShown + 1) + " / " + numberOfEntries;
}
// =========================================================================
// =========================================================================
// =============== HELPER METHODS FOR LOADING AND SAVING ===================
// =========================================================================
private void SaveData()
{
try
{
FileStream fs = new FileStream(filename, FileMode.Create, FileAccess.Write);
try
{
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(fs, dataList);
MessageBox.Show("Data saved to " + filename, "FILE SAVE OK", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch
{
MessageBox.Show("Could not serialise to " + filename,
"FILE SAVING PROBLEM", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
fs.Close();
}
catch
{
MessageBox.Show("Could not open " + filename +
" for saving.\nNo access rights to the folder, perhaps?",
"FILE SAVING PROBLEM", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
private void LoadData()
{
try
{
FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read);
try
{
BinaryFormatter bf = new BinaryFormatter();
dataList = (ArrayList)bf.Deserialize(fs);
currentEntryShown = 0;
numberOfEntries = dataList.Count;
}
catch
{
MessageBox.Show("Could not de-serialise from " + filename +
"\nThis usually happens after you changed the data structure.\nDelete the data file and re-start program\n\nClick 'OK' to close the program",
"FILE LOADING PROBLEM", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
fs.Close(); // close file
Environment.Exit(1); // crash out
}
fs.Close();
}
catch
{
if (MessageBox.Show("Could not open " + filename + " for loading.\nFile might not exist yet.\n(This would be normal at first start)\n\nCreate a default data file?",
"FILE LOADING PROBLEM", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes)
{
// No data exist yet. Create a first entry
myStruct aNewStruct = new myStruct(5);
dataList.Add(aNewStruct);
numberOfEntries = 1;
currentEntryShown = 0;
}
}
}
// =========================================================================
// =========================================================================
// ====================== HELPER METHODS FOR SORTING =======================
// =========================================================================
// This function will sort by player name by using the PlayerNameComparer below
private void sortToolStripMenuItem_Click(object sender, EventArgs e)
{
dataList.Sort(new PlayerNameComparer());
currentEntryShown = 0;
ShowData();
UpdatePrevNextBtnStatus();
}
// Overriding (= overwriting) the default IComparer
public class PlayerNameComparer : IComparer
{
public int Compare(object x, object y)
{
return ((myStruct)x).playerIgName.CompareTo(((myStruct)y).playerIgName);
}
}
private void saveButton_Click(object sender, EventArgs e)
{
SaveData();
UpdatePrevNextBtnStatus();
}
private void deletePlayerBtn_Click(object sender, EventArgs e)
{
dataList.RemoveAt(currentEntryShown);
SaveData();
if (currentEntryShown != dataList.Count)
{
ShowData();
}
UpdatePrevNextBtnStatus();
}
private void searchToolStripMenuItem_Click(object sender, EventArgs e)
{
Form searchForm = new Form1();
searchForm.Show();
}
private void uploadButton_Click(object sender, EventArgs e)
{
try
{
OpenFileDialog OpenFd = new OpenFileDialog();
pathToImage = OpenFd.FileName;
OpenFd.Filter = "Images only. |*.jpeg; *.jpg; *.png; *.gif;";
DialogResult rd = OpenFd.ShowDialog();
if (rd == System.Windows.Forms.DialogResult.OK)
{
playerPictureBox.Image = Image.FromFile(OpenFd.FileName);
myStruct aNewStruct = new myStruct(5);
aNewStruct = (myStruct)dataList[currentEntryShown];
aNewStruct.imagePath = pathToImage;
dataList[currentEntryShown] = aNewStruct;
// save the FileName to a string.
}
MessageBox.Show(pathToImage);
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message);
}
}
}
}
Set pathToImage after the ShowDIalog has completed, not before:
DialogResult rd = OpenFd.ShowDialog();
if (rd == System.Windows.Forms.DialogResult.OK)
{
pathToImage = OpenFd.FileName; ...
I could be wrong because reading all that wall of code requires too much time, but your last method should be
private void uploadButton_Click(object sender, EventArgs e)
{
try
{
OpenFileDialog OpenFd = new OpenFileDialog();
// REMOVED HERE .... pathToImage = OpenFd.FileName
OpenFd.Filter = "Images only. |*.jpeg; *.jpg; *.png; *.gif;";
DialogResult rd = OpenFd.ShowDialog();
if (rd == System.Windows.Forms.DialogResult.OK)
{
playerPictureBox.Image = Image.FromFile(OpenFd.FileName);
myStruct aNewStruct = new myStruct(5);
aNewStruct = (myStruct)dataList[currentEntryShown];
aNewStruct.imagePath = OpenFd.FileName; // Changed this line...
dataList[currentEntryShown] = aNewStruct;
}
// no much sense this here if the user cancel the dialogbox
// MessageBox.Show(pathToImage);
}
My code simply reads the file, splits it into words and whows each word in the textbox with 0.1 seconds frequency.
I click to "button1" to get the file and split.
After I click Start_Button the program gets stuck. I can't see any problem in the code. Can anyone see it please?
My code is here;
public partial class Form1 : Form
{
string text1, WordToShow;
string[] WordsOfFile;
bool LoopCheck;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog BrowseFile1 = new OpenFileDialog();
BrowseFile1.Title = "Select a text file";
BrowseFile1.Filter = "Text File |*.txt";
BrowseFile1.FilterIndex = 1;
string ContainingFolder = AppDomain.CurrentDomain.BaseDirectory;
BrowseFile1.InitialDirectory = #ContainingFolder;
//BrowseFile1.InitialDirectory = #"C:\";
BrowseFile1.RestoreDirectory = true;
if (BrowseFile1.ShowDialog() == DialogResult.OK)
{
text1 = System.IO.File.ReadAllText(BrowseFile1.FileName);
WordsOfFile = text1.Split(' ');
textBox1.Text = text1;
}
}
private void Start_Button_Click(object sender, EventArgs e)
{
timer1.Interval = 100;
timer1.Enabled = true;
timer1.Start();
LoopCheck = true;
try
{
while (LoopCheck)
{
foreach (string word in WordsOfFile)
{
WordToShow = word;
Thread.Sleep(1000);
}
}
}
catch
{
Form2 ErrorPopup = new Form2();
if (ErrorPopup.ShowDialog() == DialogResult.OK)
{
ErrorPopup.Dispose();
}
}
}
private void Stop_Button_Click(object sender, EventArgs e)
{
LoopCheck = false;
timer1.Stop();
}
private void timer1_Tick(object sender, EventArgs e)
{
textBox1.Text = WordToShow;
}
}
}
Instead of Thread.Sleep(1000); use async/await feature with Task.Delay in order to keep your UI responsible:
private async void Start_Button_Click(object sender, EventArgs e)
{
timer1.Interval = 100;
timer1.Enabled = true;
timer1.Start();
LoopCheck = true;
try
{
while (LoopCheck)
{
foreach (string word in WordsOfFile)
{
WordToShow = word;
await Task.Delay(1000);
}
}
}
catch
{
Form2 ErrorPopup = new Form2();
if (ErrorPopup.ShowDialog() == DialogResult.OK)
{
ErrorPopup.Dispose();
}
}
}