I am using express VS-2015.I have an folderbrowser control,textbox1 and button control.
I need to retrieve multiple file type and show it on listbox.I am wondering what is wrong in my code.It is not showing any error but not showing any files, despite of file type present in a folder.any suggestion.
private void button1_Click(object sender, EventArgs e)
{
FolderBrowserDialog folderBrowserDlg = new FolderBrowserDialog();
folderBrowserDlg.ShowNewFolderButton = true;
DialogResult dlgResult = folderBrowserDlg.ShowDialog();
if (dlgResult.Equals(DialogResult.OK))
{
textBox1.Text = folderBrowserDlg.SelectedPath;
Environment.SpecialFolder rootFolder = folderBrowserDlg.RootFolder;
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBox1.Text))
{
//notification to user
return;
}
string[] extensions = { ".xml", ".ddg" };
string[] dizin = Directory.GetFiles(textBox1.Text, "*.*", SearchOption.AllDirectories)
.Where(f => extensions.Contains(new FileInfo(f).Extension.ToLower())).ToArray();
listBox1.Items.AddRange(dizin);
}
Related
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.
I created an app for my dad. It's just a simple dictation program. The thing is when he installed it on his computer it stalled and said the general access denied error.
The first time it gave the error I used SaveFileDialog sfd = new SaveFileDialog() then added the usually 'if statement" to make sure the dialog was ok. However the app had an access file denied.
I did the same thing with Environment.GetFolder and it installed on his computer to the location and ran fine. However, when I use the saveFileDialog1 and openFileDialog1 out of the tool box it does not save or open a txt document.
It works on my laptop and not his. Could this be due to an error in the code vs his computer. Also what is the correct way to use the Environement.GetFolder with the SaveFileDialog.
I can also post the full code to the program if needed.
private void lblOpenFile_Click(object sender, EventArgs e)
{
OpenFileDialog open = new OpenFileDialog();
open.Title = "Open File";
open.Filter = "Text Files (*txt) | *.txt";
if (open.ShowDialog() == DialogResult.OK)
{
StreamReader read = new StreamReader(File.OpenRead(open.FileName));
txtTextBox.Text = read.ReadToEnd();
read.Dispose();
}
}
private void lblSaveFile_Click(object sender, EventArgs e)
{
SaveFileDialog save = new SaveFileDialog();
save.Title = "Save File";
save.Filter = "Text Files (*txt) | *.txt";
if (save.ShowDialog() == DialogResult.OK)
{
StreamWriter write = new StreamWriter(File.Create(save.FileName));
write.Write(txtTextBox.Text);
write.Dispose();
}
}
This is the Enviroment i used on my screen recorder. i when i click save it brings up a dialog box i put in the file name press save and it does nothing. It saves the file but not as i specified. So i am trying to merge the above and below codes. The above code does not grant access however the below does
string OutputPath;
OutputPath = Environment.GetFolderPath(Environment.SpecialFolder.MyVideos) + #"\\IvanSoft Desktop Recorder" + saveFileDialog1;
private void saveFileDialog1_FileOk(object sender, CancelEventArgs e)
{
string fileName = saveFileDialog1.FileName;
fileName = "Tutorial";
}
the whole code to the program
using System;
using System.Drawing;
using System.Windows.Forms;
using System.IO;
using System.Speech.Recognition;
using System.Threading;
namespace AGM_Speech
{
public partial class Form1 : Form
{
public SpeechRecognitionEngine recognizer;
public Grammar grammar;
public Thread RecThread;
public Boolean RecognizerState = true;
public Form1()
{
InitializeComponent();
}
private void lblAbout_Click(object sender, EventArgs e)
{
this.Hide();
About about = new About();
about.Show();
}
private void Form1_Load(object sender, EventArgs e)
{
GrammarBuilder builder = new GrammarBuilder();
builder.AppendDictation();
grammar = new Grammar(builder);
recognizer = new SpeechRecognitionEngine();
recognizer.LoadGrammarAsync(grammar);
recognizer.SetInputToDefaultAudioDevice();
recognizer.SpeechRecognized += new EventHandler<SpeechRecognizedEventArgs>(recognizer_SpeechRecognized);
RecognizerState = true;
RecThread = new Thread(new ThreadStart(RecThreadFunction));
RecThread.Start();
}
private void recognizer_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
{
if (!RecognizerState)
return;
this.Invoke((MethodInvoker)delegate
{
txtTextBox.Text += (e.Result.Text.ToLower() + " ");
txtTextBox.SelectionStart = txtTextBox.Text.Length - 0;
txtTextBox.SelectionLength = 0;
});
}
public void RecThreadFunction()
{
while (true)
{
try
{
recognizer.RecognizeAsync();
}
catch
{
}
}
}
private void lblStartSpeech_Click(object sender, EventArgs e)
{
RecognizerState = true;
}
private void lblStopSpeech_Click(object sender, EventArgs e)
{
RecognizerState = false;
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
RecThread.Abort();
RecThread = null;
grammar = null;
recognizer.UnloadAllGrammars();
recognizer.Dispose();
}
private void lblOpenFile_Click(object sender, EventArgs e)
{
string open = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
StreamReader reader = new StreamReader(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments));
}
private void lblSaveFile_Click(object sender, EventArgs e)
{
SaveFileDialog save = new SaveFileDialog();
save.Title = "Save File";
save.Filter = "Text Files (*txt) | *.txt";
if (save.ShowDialog() == DialogResult.OK)
{
StreamWriter write = new StreamWriter(File.Create(save.FileName));
write.Write(txtTextBox.Text);
write.Dispose();
}
}
private void txtSearch_Click(object sender, EventArgs e)
{
txtSearch.Clear();
lblGo_Click(null, null);
}
private void txtSearch_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)ConsoleKey.Enter)
{
lblGo_Click(null, null);
}
}
private void lblGo_Click(object sender, EventArgs e)
{
int index = 0;
String temp = txtTextBox.Text;
txtTextBox.Text = "";
txtTextBox.Text = temp;
while (index <= txtTextBox.Text.LastIndexOf(txtSearch.Text))
{
txtTextBox.Find(txtSearch.Text, index, txtTextBox.TextLength, RichTextBoxFinds.None);
txtTextBox.SelectionColor = Color.YellowGreen;
index = txtTextBox.Text.IndexOf(txtSearch.Text, index) + 1;
}
}
}
}
It's hard to say where you're failing, because there isn't much in the way of try/catch or logging.
Can you use this instead, and paste the stack trace that shows in the Message Box?
private string fileOutputLocation { get; set; }
private void lblSaveFile_Click(object sender, EventArgs e)
{
bool fileSelected = false;
Try(() =>
{
SaveFileDialog save = new SaveFileDialog();
save.Title = "Save File";
save.Filter = "Text Files (*txt) | *.txt";
save.InitialDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyVideos), "IvanSoft Desktop Recorder");
if (save.ShowDialog() == DialogResult.OK)
{
fileOutputLocation = save.FileName;
fileSelected = true;
}
});
if (fileSelected)
{
bool fileSaved = SaveFile();
MessageBox.Show("File saved successfully: " + fileSaved.ToString());
}
}
private bool SaveFile()
{
TryDeleteFile();
bool fileSaved = false;
Try(()=>
{
File.WriteAllText(fileOutputLocation, txtTextBox.Text);
fileSaved = true;
});
return fileSaved;
}
private void TryDeleteFile()
{
Try(()=>
{
if (File.Exists(fileOutputLocation))
{
File.Delete(fileOutputLocation);
}
});
}
private void Try(Action action)
{
try
{
action();
}
catch (Exception e)
{
MessageBox.Show(string.Format("The following exception was thrown:\r\n{0}\r\n\r\nFile path: {1}", e.ToString(), fileOutputLocation));
}
}
With this, plus the events logged to the Windows Event Viewer (Start>Run>Eventvwr>Security), we should be able to tell you what the problem is.
Lastly, if you're just providing an executable to run, you should check the properties of the file to ensure it's not blocked in Windows.
I have code like this:
private void button1_Click(object sender, EventArgs e)
{
openFileDialog1.ShowDialog();
}
private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
{
string ext = Path.GetExtension(openFileDialog1.FileName);
if(string.Compare(ext, ".FDB") == 0)
{
string fileName = openFileDialog1.SafeFileName;
string fileDirectory = Path.GetDirectoryName(openFileDialog1.FileName);
string databaseTxt = #"C:\Users\arist\AppData\Roaming\TDWork\";
string[] database = { fileDirectory + fileName };
if (Directory.Exists(databaseTxt))
{
System.IO.File.WriteAllLines(databaseTxt + "databases.txt", database);
}
else
{
DirectoryInfo di = Directory.CreateDirectory(databaseTxt);
System.IO.File.WriteAllLines(databaseTxt + "databases.txt", database);
}
}
else
{
MessageBox.Show("Fajl koji ste izabrali nije Firebird baza (.FDB)");
e.Cancel = true;
}
}
Now, i want to create more buttons that open same file dialog. Problem is that i want to pass openFileDialog directory to different textboxes. So logic is this:
If i open with button1, pass value to textbox1,
If i open with button2, pass value to textbox2,
if i open with button3, pass value to textbox3.
So i wanted to create int check (1, 2, 3) so when i press button1, it pass check = 1 to OpenDialog1_FileOk, so i just do switch there and do actions.
Problem is i do not know how to pass it to handler, and if that is possible. Also if there is any other solution, please write it.
First, you could use your openfiledialog just like this, without handling a whole new function for it:
if(openFileDialog1.ShowDialog() == DialogResult.OK){
//...code
}
Second, for your goal you'll have to be sure that the names of your controls are exactly ending on the digit you want (e.g. "button1" and "textbox1"). Then you can do it like this:
void Button1Click(object sender, EventArgs e)
{
//MessageBox.Show(bt.Name[bt.Name.Length - 1].ToString());
if(openFileDialog1.ShowDialog() == DialogResult.OK)
{
if(!Path.GetExtension(openFileDialog1.FileName).EndsWith(".FDB")) //checking if the extension is .FDB (as you've shown in your example)
{
MessageBox.Show("Fajl koji ste izabrali nije Firebird baza (.FDB)");
return; //return if it's not and no further code gets executed
}
string fileDirectory = Path.GetDirectoryName(openFileDialog1.FileName); //getting the directory
string nameOfMyButton = (sender as Button).Name; //you get the name of your button
int lastDigitOfMyName = Convert.ToInt16(Name[Name.Length - 1]); //returns the number of your button
TextBox neededTextboxToShowDirectory = this.Controls.Find("textbox" + lastDigitOfMyName, true).FirstOrDefault() as TextBox; //this will search for a control with the name "textbox1"
neededTextboxToShowDirectory.Text = fileDirectory; //you display the text
//... doing the rest of your stuff here
}
}
You could use a private field where you save temporarily the text of your TextBox and deploy it in the click event like this:
private int whichButton = 0;
private void button1_Click(object sender, EventArgs e)
{
whichButton = 1;
openFileDialog1.ShowDialog();
}
private void button2_Click(object sender, EventArgs e)
{
whichButton = 2;
openFileDialog1.ShowDialog();
}
private void button3_Click(object sender, EventArgs e)
{
whichButton = 3;
openFileDialog1.ShowDialog();
}
use then the whichButton to choose
private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
{
switch (whichButton)
{
....
}
}
I have the following code that list the files that i drag in a listbox.
now i need to filter so it can only list PDF files and discard the rest.
private void Form1_Load(object sender, EventArgs e)
{
listBoxFiles.AllowDrop = true;
listBoxFiles.DragDrop += listBoxFiles_DragDrop;
listBoxFiles.DragEnter += listBoxFiles_DragEnter;
}
private void listBoxFiles_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
e.Effect = DragDropEffects.Copy;
}
private void listBoxFiles_DragDrop(object sender, DragEventArgs e)
{
string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
foreach (string file in files)
listBoxFiles.Items.Add(file);
}
Try this:
private void listBoxFiles_DragDrop(object sender, DragEventArgs e)
{
string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
foreach (string file in files)
{
if (Path.GetExtension(file) == "pdf")
{
listBoxFiles.Items.Add(file);
}
}
}
Also, if it works - you can make it in one line with Linq
How can I limit the number of files to be uploaded using the multi-select openfiledialog in c#?
Here's my code:
private void btn_upload_Click(object sender, EventArgs e)
{
OpenFileDialog op1 = new OpenFileDialog();
op1.Multiselect = true;
op1.ShowDialog();
op1.Filter = "allfiles|*.xls";
textBox1.Text = op1.FileName;
int count = 0;
string[] FName;
foreach (string s in op1.FileNames)
{
FName = s.Split('\\');
File.Copy(s, "C:\\file\\" + FName[FName.Length - 1]);
count++;
}
MessageBox.Show(Convert.ToString(count) + " File(s) copied");
}
It will upload as how much the user wants to. But I want to limit it by 5 files only.
You can't do that directly but you can check the selected files count and display a message to user:
if(op1.FileNames.Length > 5)
{
MessageBox.Show("your message");
return;
}
Or you can take the first five file from selected files:
foreach (string s in op1.FileNames.Take(5))
{
...
}
I just tested and this works:
private void btn_upload_Click(object sender, EventArgs e)
{
OpenFileDialog op1 = new OpenFileDialog();
op1.Multiselect = true;
op1.FileOk += openFileDialog1_FileOk; // Event handler
op1.ShowDialog();
// etc
}
void openFileDialog1_FileOk(object sender, CancelEventArgs e)
{
OpenFileDialog dlg = sender as OpenFileDialog;
if (5 < dlg.FileNames.Length)
{
MessageBox.Show("Too Many Files");
e.Cancel = true;
}
}