I am making a program that allows you to roll five different types of multi sided "dice", and when you roll a number I want it to store it in a text file. There is a menu strip item at the top of my form that you click, it closes the StreamWriter and FileStream and opens a second form showing what numbers were rolled and by what die they were rolled ( I'm having it be just the numbers rolled now for simplicity's sake) and it displays fine. But when I close the Reader, Stream, and second form and go back to the first form, I try to Reopen the Writer and Stream and it tells me that is already in use.
My First Form's Code:
using System;
using System.Windows.Forms;
using System.IO;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
private Random ran = new Random();
static FileStream outFile = new FileStream(#"H:\C#\Independant Projects\VirtualDice\History.txt", FileMode.OpenOrCreate, FileAccess.Write);
StreamWriter writer = new StreamWriter(outFile);
private int ranNum;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
ranNum = ran.Next(1, 21);
Display();
}
private void button2_Click(object sender, EventArgs e)
{
ranNum = ran.Next(1, 13);
Display();
}
private void button3_Click(object sender, EventArgs e)
{
ranNum = ran.Next(1, 5);
Display();
}
private void button4_Click(object sender, EventArgs e)
{
ranNum = ran.Next(1, 9);
Display();
}
private void button5_Click(object sender, EventArgs e)
{
ranNum = ran.Next(1, 11);
Display();
}
private void Display()
{
lblNum.Text = String.Format("{0}", ranNum);
lblNum.Visible = true;
writer.WriteLine(ranNum);
}
private void historyToolStripMenuItem_Click(object sender, EventArgs e)
{
tabControl1.SelectedIndex = 1;
writer.Close();
outFile.Close();
History history = new History();
history.ShowDialog();
}
private void button1_Click_1(object sender, EventArgs e)
{
FileStream outFile = new FileStream(#"H:\C#\Independant Projects\VirtualDice\History.txt", FileMode.OpenOrCreate, FileAccess.Write);
StreamWriter writer = new StreamWriter(outFile);
tabControl1.SelectedIndex = 0;
}
}
}
My Second Form's Code:
using System;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class History : Form
{
public History()
{
InitializeComponent();
}
static private FileStream inFile = new FileStream(#"H:\C#\Independant Projects\VirtualDice\History.txt", FileMode.Open, FileAccess.Read);
private StreamReader reader = new StreamReader(inFile);
private void History_Load(object sender, EventArgs e)
{
string item;
item = reader.ReadLine();
try
{
lstHistory.Items.Add(item);
}
catch (Exception)
{
lstHistory.Font = new Font(lstHistory.Font.Name, 12, lstHistory.Font.Unit);
lstHistory.Items.Add("You have not rolled any numbers");
}
}
}
}
You need to release the unmanaged resources (in your case the file) properly once done with it. Call the Dispose() function on the stream once done with it:
if(inFile != null){
inFile.Dispose();
}
And even better, wrap it in a using() like this:
using(FileStream outFile = new FileStream(#"H:\C#\Independant Projects\VirtualDice\History.txt", FileMode.OpenOrCreate, FileAccess.Write)){
StreamWriter writer = new StreamWriter(outFile);
tabControl1.SelectedIndex = 0;
}
using will automatically call Dispose() for you at the right time in the proper way (i.e. it checks if the object is null first before calling Dispose() on it to avoid a `null exception). Check this link for more details about the using statement.
However, if you have the same code in so many places, it is probably worth it to wrap it in a singleton pattern. Check this Microsoft article on how to write a singleton pattern in C#.
Related
I already got most of the help I needed in order to create a working button to save my scraped proxies to a .txt file, but I still run into one issue. This is the code that I have gotten so far, it works perfectly fine:
using System;
using System.Text;
using System.Text.RegularExpressions;
using System.Net;
using System.Windows.Forms;
using System.IO;
namespace CyberScraper
{
public partial class Base_Scraper : Form
{
WebClient _WC = new WebClient();
Defaults _DF = new Defaults();
public Base_Scraper()
{
CheckForIllegalCrossThreadCalls = false;
InitializeComponent();
}
private void Base_Scraper_Load(object sender, EventArgs e)
{
MessageBox.Show("twitch.tv/CyberLost same YT Name");
}
private void ScrapeTheProxies()
{
try
{
foreach (string Source in ScrapeSources.Lines)
{
string UnparsedWebSource = _WC.DownloadString(Source);
MatchCollection _MC = _DF.REGEX.Matches(UnparsedWebSource);
foreach (Match Proxy in _MC)
{
GatheredProxies.Items.Add(Proxy);
}
}
}
catch (Exception)
{
}
}
private void SaveProxyResults_Click(object sender, System.EventArgs e)
{
Stream myStream;
SaveFileDialog dlg = new SaveFileDialog();
dlg.Title = "";
dlg.InitialDirectory = #"C:\Users\username\Desktop";
dlg.Filter = "txt files (*.txt)|*.txt";
dlg.FilterIndex = 1;
if (dlg.ShowDialog() == DialogResult.OK)
{
if ((myStream = dlg.OpenFile()) != null)
{
myStream.Close();
StreamWriter writer = new StreamWriter(dlg.FileName);
for (int i = 0; i < GatheredProxies.Items.Count; i++)
{
writer.WriteLine((string)GatheredProxies.Items[i]);
}
writer.Close();
}
}
dlg.Dispose();
}
private void BackgroundWorker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
ScrapeTheProxies();
}
private void ScrapeButton_Click(object sender, EventArgs e)
{
BackgroundWorker.RunWorkerAsync();
}
}
}
When I click on "Save Results" it works before I scraped the proxies, if I do it after finishing scraping the proxies it outputs this error and saves it on the desktop as an empty .txt file instead of a .txt file containing the scraped proxies:
System.InvalidCastException: 'Unable to cast object of type 'System.Text.RegularExpressions.Match' to type 'System.String'.'
in:
writer.WriteLine((string)GatheredProxies.Items[i]);
I want to copy an existing file to another destination, but it gives an access error.
Error Name:
System.UnauthorizedAccessException
I understand that I need to grant access but I don't know how to do this.
My project looks like:
I will put the file on the server and run this program from the web-based program. I will close the button and textbox with the source file. I will only leave the target forms open
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;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
BackgroundWorker worker = new BackgroundWorker();
public Form1()
{
InitializeComponent();
worker.WorkerReportsProgress = true;
worker.WorkerSupportsCancellation = true;
worker.ProgressChanged += Worker_ProgressChanged;
worker.DoWork += Worker_DoWork;
}
void Copyfile(string source, string des)
{
FileStream fsOut = new FileStream(des, FileMode.Create);
FileStream fsIn = new FileStream(source, FileMode.Open);
byte[] bt = new byte[1048456];
int readByte;
while ((readByte = fsIn.Read(bt, 0, bt.Length)) > 0)
{
fsOut.Write(bt,0,readByte);
worker.ReportProgress((int)(fsIn.Position * 100 / fsIn.Length));
}
fsIn.Close();
fsOut.Close();
}
private void Worker_DoWork(object sender, DoWorkEventArgs e)
{
Copyfile(txtSource.Text, txtTarget.Text);
}
private void Worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
label1.Text = progressBar1.Value.ToString() + "%";
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
FolderBrowserDialog fbd1 = new FolderBrowserDialog();
if (fbd1.ShowDialog() == DialogResult.OK)
{
txtSource.Text = Path.Combine(fbd1.SelectedPath, Path.GetFileName(txtTarget.Text));
}
}
private void button2_Click(object sender, EventArgs e)
{
worker.RunWorkerAsync();
}
private void button3_Click(object sender, EventArgs e)
{
FolderBrowserDialog fbd = new FolderBrowserDialog();
if (fbd.ShowDialog() == DialogResult.OK)
{
txtTarget.Text = Path.Combine(fbd.SelectedPath, Path.GetFileName(txtSource.Text));
}
}
}
}
I added and changed some codes
public static void CopyAll(DirectoryInfo source, DirectoryInfo target)
{
Directory.CreateDirectory(target.FullName);
// HER DOSYAYI YENI DIZINE KOPYALAR
foreach (FileInfo fi in source.GetFiles())
{
fi.CopyTo(System.IO.Path.Combine(target.FullName, fi.Name), true);
}
// HER ALT DIZINI KOPYALAR
foreach (DirectoryInfo diSourceSubDir in source.GetDirectories())
{
DirectoryInfo nextTargetSubDir =
target.CreateSubdirectory(diSourceSubDir.Name);
CopyAll(diSourceSubDir, nextTargetSubDir);
}
}
void CopyFile(string source, string des)
{
FileStream fsout = new FileStream(des, FileMode.Create);
FileStream fsIn = new FileStream(source, FileMode.Open);
byte[] bt = new byte[1048756];
int readByte;
while ((readByte=fsIn.Read(bt, 0, bt.Length))>0)
{
fsout.Write(bt, 0, readByte);
worker.ReportProgress((int)(fsIn.Position*100/fsIn.Length));
}
fsIn.Close();
fsout.Close();
}
private void Worker_DoWork(object sender, DoWorkEventArgs e)
{
CopyAll(new DirectoryInfo( txtSource.Text), new DirectoryInfo(txtTarget.Text));
}
I add my github repository:https://github.com/yusufcelik1/Copy-Folder.git
The code that I got was from naudio record sound from microphone then save and many thanks to Corey
This is the error message that I get when I run the code for the second or subsequent times.
The first time it runs, it runs with no issues what so ever.
If I change the file name it works perfectly.
Unable to copy file "obj\Debug\Basque.exe" to "bin\Debug\Basque.exe". The process cannot access the file 'bin\Debug\Basque.exe' because it is being used by another process. Basque
Could someone gave me some guidance to where I'm making my error
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 NAudio.Wave;
namespace Basque
{
public partial class FlashCard : Form
{
public WaveIn waveSource = null;
public WaveFileWriter waveFile = null;
public FlashCard()
{
InitializeComponent();
StopBtn.Enabled = false;
StartBtn.Enabled = true;
}
private void StartBtn_Click(object sender, EventArgs e)
{
StartBtn.Enabled = false;
StopBtn.Enabled = true;
waveSource = new WaveIn();
waveSource.WaveFormat = new WaveFormat(44100, 1);
waveSource.DataAvailable += new EventHandler<WaveInEventArgs>(waveSource_DataAvailable);
waveSource.RecordingStopped += new EventHandler<StoppedEventArgs>(waveSource_RecordingStopped);
waveFile = new WaveFileWriter(#"C:\Temp\bas0001.wav", waveSource.WaveFormat);
waveSource.StartRecording();
}
private void StopBtn_Click(object sender, EventArgs e)
{
StopBtn.Enabled = false;
waveSource.StopRecording();
}
void waveSource_DataAvailable(object sender, WaveInEventArgs e)
{
if (waveFile != null)
{
waveFile.Write(e.Buffer, 0, e.BytesRecorded);
waveFile.Flush();
}
}
void waveSource_RecordingStopped(object sender, StoppedEventArgs e)
{
if (waveSource != null)
{
waveSource.Dispose();
waveSource = null;
}
if (waveFile != null)
{
waveFile.Dispose();
waveFile = null;
}
StartBtn.Enabled = true;
}
private void PlayBtn_Click(object sender, EventArgs e)
{
}
private void ExitBtn_Click(object sender, EventArgs e)
{
}
}
}
It might help to put a Formclosing method with Application.Exit(); in it. If it only works on the first try, it might be because the application isn't fully closing.
You can check if this will fix it when you check task manager. Just make sure that your application isn't still there. Even if it isn't still there, the Application.Exit(); might help.
i have a new question. i have a code to load a list from binary file, i think i did it right but i need to make each variable show in its own text box. this is the ting i cannot find out how to do. can anyone help me or point me to where i can find the information?
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;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
namespace test
{
public partial class Form1 : Form
{
[Serializable]
public class ore
{
public float Titan;
public float Eperton;
}
ore b1 = null;
ore b2 = null;
public Form1()
{
InitializeComponent();
b2 = new ore();
b1 = new ore();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
float tempFloat;
if (float.TryParse(textBox1.Text, out tempFloat))
{
b1.Titan = tempFloat;
}
else
MessageBox.Show("uh oh");
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
float tempFloat;
if (float.TryParse(textBox1.Text, out tempFloat))
{
b2.Eperton = tempFloat;
}
else
MessageBox.Show("uh oh");
}
private void button1_Click(object sender, EventArgs e)
{
List<ore> oreData = new List<ore>();
oreData.Add(b1);
oreData.Add(b2);
FileStream fs = new FileStream("ore.dat", FileMode.Create);
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(fs, oreData);
fs.Close();
}
private void textBox3_TextChanged(object sender, EventArgs e)
{
}
private void textBox4_TextChanged(object sender, EventArgs e)
{
}
List<ore> books = new List<ore>();
private void button2_Click(object sender, EventArgs e)
{
FileStream fs = new FileStream("ore.dat", FileMode.Open);
BinaryFormatter bf = new BinaryFormatter();
List<ore> books = (List<ore>)bf.Deserialize(fs);
fs.Close();
if (books.Count > 1)
{
textBox3.Text = books[0];//update the first text
textBox4.Text = books[1];//update the second text
}
}
}
}
Windows Forms:
1- Define your List books at class level so you can use it in another methods if needed..
2-
public clas MyForm : Form
{
List<ore> books = new List<ore>();//define at the class scope
private void button2_Click(object sender, EventArgs e)
{
FileStream fs = new FileStream("ore.dat", FileMode.Open);
BinaryFormatter bf = new BinaryFormatter();
books = (List<ore>)bf.Deserialize(fs);
fs.Close();
if (books.Count > 1)
{
textBox3.Text = books[0];//update the first text
textBox4.Text = books[1];//update the second text
}
}
}
If you need collection of list boxes to be added and removed whenever a book list changes then this is another story... write a comment or update your question...
One solution is to use ListView control instead of a bunch of Textboxs. In the template of Listview, put Textbox control and bind it to your List object.
Alternatively, create Textbox control on the fly.
for(int i=1; i<=books.Count; i++)
{
var textBoxCtrl = new TextBox()
textBoxCtrl.ID = "TextBox"+i.toString();
textBoxCtrl.Text = books[i];
Page.Controls.Add(textBoxCtrl);
}
In ASP.NET:
You can use the ASP.NET FormView object to create your form and then bind the dataset to the form and call the DataBind.
<asp:FormView runat="server" ID="form1">
<ItemTemplate>
<asp:TextBox Text='<%# Bind("") %>'></asp:TextBox>
</ItemTemplate>
</asp:FormView>
I was trying to convert an ink from Microsoft.Ink namespace to memorystream, so to convert it to image, but I don't understand why it's getting an error in the memorystream. I kind of felt that it was an error from Convert.FromBase64String()
But I don't know what other choices I have to convert it to image.
Please help me
Here is my code:
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;
using System.IO;
using Microsoft.Ink;
namespace testPaint
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
InkCollector ink;
private void Form1_Load(object sender, EventArgs e)
{
ink = new InkCollector(pictureBox1);
ink.Enabled = true;
ink.AutoRedraw = true;
}
private void btnSave_Click(object sender, EventArgs e)
{
UTF8Encoding utf8 = new UTF8Encoding();
ink.Enabled = false;
string strInk = Convert.ToBase64String(ink.Ink.Save(PersistenceFormat.Base64InkSerializedFormat, CompressionMode.Maximum));
textBox1.Text = strInk;
ink.Enabled = true;
}
private void btnClr_Click(object sender, EventArgs e)
{
ink.Enabled = false;
ink.Ink = new Microsoft.Ink.Ink();
ink.Enabled = true;
pictureBox1.Invalidate();
}
private void btnExport_Click(object sender, EventArgs e)
{
byte[] byImage = Convert.FromBase64String(textBox1.Text);
MemoryStream ms = new MemoryStream();
ms.Write(byImage, 0, byImage.Length);
Image img = Image.FromStream(ms);
img.Save("test.gif", System.Drawing.Imaging.ImageFormat.Gif);
ink.Enabled = true;
}
}
}
The documentation is very preliminary but I think you are probably using the wrong PersistenceFormat tag: you are using Base64 as the output format but you clearly want PersistenceFormat.Gif.
Apart from that, your conversion to and from a string is really not at all meaningful. Just use a private byte[] variable to store the ink data. Furthermore, your detour via a MemoryStream and a System.Graphics.Image makes no sense either.
// using System.IO;
private byte[] inkData;
private void btnSave_Click(object sender, EventArgs e)
{
inkData = ink.Ink.Save(PersistenceFormat.Gif, CompressionMode.Maximum);
}
private void btnExport_Click(object sender, EventArgs e)
{
// Data is already in GIF format, write directly to file!
using (var stream = new FileStream("filename", FileMode.Create, FileAccess.Write))
stream.Write(inkData, 0, inkData.Length);
}