I am trying to put together a form application to browse and play WAV files. Currently, it has two buttons - one to browse and select the WAV, the other one is to play. I have implemented the browse button and it is working ok. I checked it by playing the WAV sound within the button, as you can see:
private void Browse_Click(object sender, EventArgs e) {
OpenFileDialog tarik = new OpenFileDialog();
tarik.Title = "Browse...";
tarik.InitialDirectory = #"Desktop";
tarik.Filter = "Wav files (*.wav)|*.wav";
tarik.RestoreDirectory = true;
if (tarik.ShowDialog() == DialogResult.OK) {
textBox1.Text = tarik.FileName;
Stream tarik2 = tarik.OpenFile();
SoundPlayer snd = new SoundPlayer(tarik2);
snd.Play();
}
}
I tested the code and it is working, but when I try to call the 'tarik' from another button:
private void Play_Click(object sender, EventArgs e) {}
As shown above, it says I am not allowed to do this.
The variables that you create in your browse handler are local variables (as they should be) which means they can't be accessed (because they don't exist) once the method ends.
You'll need to create an instance field, which exists for the entire lifetime of the object, to allow the other method to access it:
//new instance field.
private string tarikFileName;
private void Browse_Click(object sender, EventArgs e)
{
OpenFileDialog tarik = new OpenFileDialog();
tarik.Title = "Browse...";
tarik.InitialDirectory = #"Desktop";
tarik.Filter = "Wav files (*.wav)|*.wav";
tarik.RestoreDirectory = true;
if (tarik.ShowDialog() == DialogResult.OK) {
//store value in instance field
tarikFileName = tarik.FileName;
textBox1.Text = tarik.FileName;
Stream tarik2 = tarik.OpenFile();
using(SoundPlayer snd = new SoundPlayer(tarik2))
snd.Play();
}
}
private void Play_Click(object sender, EventArgs e)
{
if(tarikFileName != null)
{
Stream stream = File.OpenRead(tarikFileName);
using(SoundPlayer snd = new SoundPlayer(stream))
snd.Play();
}
}
Also note that the SoundPlayer should be disposed when you're done with it, so I've wrapped it in a using block to ensure that happens.
I'd suggest the following approach:
Declare the SoundPLayer as a variable of your Form.
In the handler of Browse button get the file name, create a stream and initialize your SoundPlayer with it.
In the handler of Play button call the Play() method of the SoundPlayer.
In order to share data across the two methods you need some place to store the references. In your case I would recommend pulling the file name from textBox1.Text. That way you don't have to worry about managing (opening/closing) the stream in multiple places.
private void Browse_Click(object sender, EventArgs e)
{
OpenFileDialog tarik = new OpenFileDialog();
tarik.Title = "Browse...";
tarik.InitialDirectory = #"Desktop";
tarik.Filter = "Wav files (*.wav)|*.wav";
tarik.RestoreDirectory = true;
if (tarik.ShowDialog() == DialogResult.OK) {
textBox1.Text = tarik.FileName;
}
}
private void Play_Click(object sender, EventArgs e)
{
using(Stream tarik2 = File.Open(textBox1.Text, FileMode.Open))
{
SoundPlayer snd = new SoundPlayer(tarik2);
snd.Play();
}
}
Related
Goal: Direct print a CSV file which is selected from another button on my forms application
Problem: I don't know how to tell amy btnPrintFile_click method the FileName coming from another method in form1.cs
Any help would be appreciated, Im new to forms in c#
public void openCVSFile(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Multiselect = false;
ofd.Filter = "CSV files (*.csv)|*.csv";
ofd.FilterIndex = 1;
if(ofd.ShowDialog() == DialogResult.OK)
{
txtAddressCount.Text = ("Address count: "+ ofd.FileName);
}
}
private void btnPrintFile_Click(object sender, EventArgs e)
{
try
{
streamToPrint = new StreamReader(ofd.FileName);
try
{
printFont = new Font("Arial", 10);
PrintDocument pd = new PrintDocument();
pd.PrintPage += new PrintPageEventHandler
(this.pd_PrintPage);
pd.Print();
}
finally
{
streamToPrint.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
For reference I'm using this article from Microsoft
https://learn.microsoft.com/en-us/dotnet/api/system.drawing.printing.printdocument?redirectedfrom=MSDN&view=dotnet-plat-ext-6.0
public void openCVSFile(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
...
}
...
private void btnPrintFile_Click(object sender, EventArgs e)
{
try
{
streamToPrint = new StreamReader(ofd.FileName);
^^^
ofd was declared in the other method
Im new to forms in c#
This isn't about forms; you can never reach a variable declared inside one method, from another method.. the variable has to be passed from one method to the other, or it has to be declared at a scope that both methods can access.
Declare your OpenFileDialog under the class instead:
class YourForm: Form{
private OpenFileDialog ofd = new OpenFileDialog();
or drop it onto the form in the designer so it appears in the tray under the form view:
And rename it so it is called ofd by altering the (Name) line in the property grid:
Either of these ways make it accessible to all methods in the class. Doing it the visual way probably makes life easier in terms of setting other properties like the initial folder, file filter etc
I would like to create application in which I could create file, write something into it by button clicking and then close this file by clicking another button. The problem is that when I've declared Streamwrtier object within one button I couldn't invoke file close method from within second button because I've got such error: the name 'file' does not exist in the current context. When I initiate Streamwriter outside the button method problem dissapeares but then file is being created before I will click button. Do you know how could I overcome this issue?
public void button1_Click(object sender, EventArgs e)
{
button1.Visible = false;
button2.Visible = true;
StreamWriter file = new StreamWriter("test.txt");
file.WriteLine(value.ToString());
}
private void button2_Click(object sender, EventArgs e)
{
button1.Visible = true;
button2.Visible = false;
file.Close();
}
Here's the basic fix:
private StreamWriter file = null;
public void button1_Click(object sender, EventArgs e)
{
button1.Visible = false;
button2.Visible = true;
if (file == null)
file = new StreamWriter("test.txt");
file.WriteLine(value.ToString());
}
private void button2_Click(object sender, EventArgs e)
{
button1.Visible = true;
button2.Visible = false;
if (file is object)
file.Close();
}
But really, it's poor practice in most cases to hold the file open. You generally want something more like this, which handles opening and closing the necessary streams all in one go, and only keeps the file open for the minimum necessary duration:
public void button1_Click(object sender, EventArgs e)
{
File.AppendAllText("test.txt", value.ToString());
}
And since we always close the file right away, the second button isn't needed at all.
I am creating an app that i need to copy some png files.
I already have searching with many keywords, finding many solutions and none of them worked, so i decided to ask here.
There is the code,it uses a windows forms and "this" refers to this window
private void button2_Click(object sender, EventArgs e)
{
//yes i commented them to solve why the file was not copying
//try
{
FileInfo x = new FileInfo(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + #"\some_location");
x.CopyTo(textBox1.Text);
}
//catch
{ }
this.Close();
}
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog openDialog = new OpenFileDialog();
openDialog.Title = "Select Image To Load";
openDialog.Filter = "Text Files (*.png)|*.png" + "|" + "All Files (*.*)|*.*";
if (openDialog.ShowDialog() == DialogResult.OK)
{
string PathData = openDialog.FileName;
textBox1.Text = PathData;
}
}
I have gotten several different errors, but most common there is:
System.UnauthorizedAccessException
It looks a bit weird to me that you're using an OpenFileDialog to select a destination. I'd assume you'd want to either do it the other way around:
private void button2_Click(object sender, EventArgs e)
{
//yes i commented them to solve why the file was not copying
//try
{
FileInfo x = new FileInfo(textBox1.Text);
x.CopyTo(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + #"\some_location");
}
//catch
{ }
this.Close();
}
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog openDialog = new OpenFileDialog();
openDialog.Title = "Select Image To Load";
openDialog.Filter = "Text Files (*.png)|*.png" + "|" + "All Files (*.*)|*.*";
if (openDialog.ShowDialog() == DialogResult.OK)
{
string PathData = openDialog.FileName;
textBox1.Text = PathData;
}
}
or use SaveFileDialog instead.
void OpenWithDialog()
{
var ofd = new OpenFileDialog();
ofd.Filter = "Triangle polygon file|*.poly";
if (ofd.ShowDialog() == DialogResult.OK)
{
OpenPolyFile(ofd.FileName);
}
}
void OpenPolyFile(string file)
{
var geometry = TriangleNet.IO.FileReader.ReadPolyFile(file);
// ...
}
private void button1_Click(object sender, EventArgs e)
{
}
How to read files in button1 click directly?
what you want is that your geometry object be accessible in additional scopes besides OpenPolyFile(). So you can simply make the geometry declaration accessible to both methods, declaring it, say, in the form code behind
// class scoped variables
[ThePolyFileType] (pick the right one here :) geometry = null;
void OpenWithDialog()
{
var ofd = new OpenFileDialog();
ofd.Filter = "Triangle polygon file|*.poly";
if (ofd.ShowDialog() == DialogResult.OK)
{
OpenPolyFile(ofd.FileName);
}
}
void OpenPolyFile(string file)
{
geometry = TriangleNet.IO.FileReader.ReadPolyFile(file);
// ...
}
private void button1_Click(object sender, EventArgs e)
{
if (geometry != null)
{
//do your stuff
}
}
How do i read already opened file in a another button click event
directly .(i.e without open file dialogue in button click)
I'm not quite sure why you want to read it twice, but if that requirement says, make selected filename available globally and use it.
private string filename;
void OpenWithDialog()
{
var ofd = new OpenFileDialog();
ofd.Filter = "Triangle polygon file|*.poly";
if (ofd.ShowDialog() == DialogResult.OK)
{
OpenPolyFile(ofd.FileName);
filename = ofd.FileName
}
}
Now you have opened filename available in button_clcik you can use this file and read again.
private void button1_Click(object sender, EventArgs e)
{
// now you can read the file.
//File.ReadAllText(filename); //OR
TriangleNet.IO.FileReader.ReadPolyFile(file);
}
I'm trying to open a file dialog box so the user can choose the location of an access database. Can someone explain how to add a file dialog when a button is clicked and also how to transform the user choice into a string that contains the file directory ( c:\abc\dfg\1234.txt)?
Thanks
As you did not state the technology you use (WPF or WinForms), I assume you use WinForms. In that case, use an OpenFileDialog in your code. After the dialog was closed, you can get the selected full file name using the FileName property.
There is the following example of how to use it on the documentation page I linked above, which I modified slightly as you want the file name, not the stream:
private void button1_Click(object sender, System.EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = "c:\\" ;
openFileDialog1.Filter = "Database files (*.mdb, *.accdb)|*.mdb;*.accdb" ;
openFileDialog1.FilterIndex = 0;
openFileDialog1.RestoreDirectory = true ;
if(openFileDialog1.ShowDialog() == DialogResult.OK)
{
string selectedFileName = openFileDialog1.FileName;
//...
}
}
Based on your previous question I assume you are using WinForms.
You can use the OpenFileDialog Class for this purpose. See the code below which will run on your button Click event assuming your button id is button1:
private void button1_Click(object sender, System.EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = "c:\\";
openFileDialog1.Filter = "Access files (*.accdb)|*.accdb|Old Access files (*.mdb)|*.mdb";
openFileDialog1.FilterIndex = 2;
openFileDialog1.RestoreDirectory = true;
if(openFileDialog1.ShowDialog() == DialogResult.OK)
{
var path = openFileDialog1.FileName;
}
}
More information.
Assuming that you actually have a form with button (button1)...
At the constructor hook into button1's click event
...
button1.Click += button1_Click;
...
Then define the handling function and use System.Windows.Forms.OpenFileDialog as you like.
void button1_Click(object sender, EventArgs e)
{
string oSelectedFile = "";
System.Windows.Forms.OpenFileDialog oDlg = new System.Windows.Forms.OpenFileDialog();
if (System.Windows.Forms.DialogResult.OK == oDlg.ShowDialog())
{
oSelectedFile = oDlg.FileName;
// Do whatever you want with oSelectedFile
}
}
It's actually fairly simple
namespace YourProgram
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
string path = "";
//Declare the File Dialog
OpenFileDialog ofd = new OpenFileDialog();
private void button1_click(object sender, EventArgs e)
{
if (odf.ShowDialog() == DialogResult.OK)
{
path = ofd.FileName;
}
}
}
}