I am generation json which show something like this (var json): ["C:\Users\Admin\Desktop\222.mp3","C:\Users\Admin\Desktop\TGD.mp3"]
How can I parse it with "foreach"? I want to use everysingle link in my app.
private void Button_Click_7(object sender, RoutedEventArgs e)
{
// Eksport
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "Json (*.json)|*.json";
if (saveFileDialog.ShowDialog() == true)
{
string strResultJson = JsonConvert.SerializeObject(MusicList);
File.WriteAllText(saveFileDialog.FileName, strResultJson);
MessageBox.Show("Twoja playlista zostaĆa zapisana!");
}
}
private void Button_Click_8(object sender, RoutedEventArgs e)
{
// Import
OpenFileDialog fileDialog = new OpenFileDialog
{
Multiselect = false,
DefaultExt = ".json"
};
bool? dialogOk = fileDialog.ShowDialog();
if (dialogOk == true)
{
string linkToPlaylist;
linkToPlaylist = fileDialog.FileName;
var json = new WebClient().DownloadString(linkToPlaylist);
// What's now?
MessageBox.Show(json.ToString());
}
}
Related
so I am writing a c# program which will return a text file selected in a textbox a string[].
But when trying to do this it gets an error saying "a static local function cannot contain a reference to this or base".
Here is the code for collecting the textbox string
string[] words = { File.ReadAllText(dicuploadname.Text)
This is where the error appears. The code for the textbox in question is as follows:
Private void uploaddict_Click(object sender, EventArgs e)
{
OpenFileDialog fdlg = new OpenFileDialog();
MessageBox.Show("The dictionary will need to be a .txt file.");
fdlg.Title = "Select your dictionary file";
fdlg.InitialDirectory = #"c:\";
fdlg.Filter = "Text files (*.txt)|*.txt";
fdlg.FilterIndex = 2;
fdlg.RestoreDirectory = true;
if (fdlg.ShowDialog() == DialogResult.OK)
{
dicuploadname.Text = fdlg.FileName;
}
}
public static void dicuploadname_TextChanged(object sender, EventArgs e)
{
}
public string text = dicuploadname.Text;
}
}
Also included is the code for the browse button that selects the text file and pastes it's location to the textbox.
Not sure how to return the contents of the text file as a string[]? Thanks.
Newest code:
else
{
var myInt = int.Parse(min.Text);
int seconds = myInt * 60000;
System.Timers.Timer aTimer = new System.Timers.Timer();
aTimer.Elapsed += new ElapsedEventHandler(TimerMethod);
aTimer.Interval = seconds;
aTimer.Enabled = true;
// Do something with t...
string uriString = "https://open.spotify.com/search/";
static void TimerMethod(object source, ElapsedEventArgs e)
{
string uriString = "https://open.spotify.com/search/";
WebClient webClient = new WebClient();
Random r = new Random();
string words;
words = File.ReadAllText(dicuploadname.Text);
Console.WriteLine(words[r.Next(0, words.Length)]);
string word = words[r.Next(0, words.Length)];
NameValueCollection nameValueCollection = new NameValueCollection();
nameValueCollection.Add(uriString, word);
webClient.QueryString.Add(nameValueCollection);
var spotifysearch = new ProcessStartInfo
{
FileName = "https://open.spotify.com/search/" + word,
UseShellExecute = true
};
Process.Start(spotifysearch);
}
}
}
private void HiveMind_Click_1(object sender, EventArgs e)
{
var HiveMind= new HiveMind();
HiveMind.Show();
}
private void uploaddict_Click(object sender, EventArgs e)
{
string[] words;
OpenFileDialog fdlg = new OpenFileDialog();
fdlg.Title = "Select your dictionary file";
fdlg.InitialDirectory = #"c:\";
fdlg.Filter = "Text files (*.txt)|*.txt";
fdlg.RestoreDirectory = true;
if (fdlg.ShowDialog() == DialogResult.OK)
words = File.ReadAllText(fdlg.FileName).Split(' ');
}
public string words;
private void dicuploadname_TextChanged(object sender, EventArgs e)
{
}
}
}
Looking at your posted code, dicuploadname is not a variable but a event handler. Change it to this, which assigns the variable words by reading the user specified text file and splitting it on the space character.
private void uploaddict_Click(object sender, EventArgs e)
{
string[] words;
OpenFileDialog fdlg = new OpenFileDialog();
fdlg.Title = "Select your dictionary file";
fdlg.InitialDirectory = #"c:\";
fdlg.Filter = "Text files (*.txt)|*.txt";
fdlg.RestoreDirectory = true;
if (fdlg.ShowDialog() == DialogResult.OK)
words = File.ReadAllText(fdlg.FileName).Split(' ');
}
In this code the file the user picks is split on the space character. If you just wanted a string of the code and not each word change the declaration of words to
string words;
and the line where the variable gets assigned to
words = File.ReadAllText(fdlg.Filename);
hope this helps
I am trying to save some selected file in a folder(images) inside my application
I am able to get the file using following code:
private void button1_Click(object sender, EventArgs e)
{
string imagelocation = "";
OpenFileDialog dialog = new OpenFileDialog();
if(dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK )
{
textBox2.Text = dialog.FileName;
}
}
For saving the file I got in textBox2, I tried following code. But with following code I have to also select the path where I want to save the file.
What If I want to (set my path permanently to 'images' folder as shown in pic) for saving?
private void button2_Click(object sender, EventArgs e)
{
SaveFileDialog f = new SaveFileDialog();
if(f.ShowDialog() == DialogResult.OK)
{
using(Stream s = File.Open(f.FileName, FileMode.CreateNew))
using(StreamWriter sw = new StreamWriter(s))
{
sw.Write(textBox2.Text);
}
}
}
2 Approaches to Solve this problem
First Approach: (Browser the File and click Save, to automatically save the selected file to Image Directory)
private void button2_Click(object sender, System.EventArgs e)
{
var assemblyPath = System.Reflection.Assembly.GetExecutingAssembly().Location;
var assemblyParentPath = Path.GetDirectoryName(assemblyPath);
var imageDir = Path.Combine(assemblyParentPath, "Image");
if (!Directory.Exists(imageDir))
Directory.CreateDirectory(imageDir);
using (Stream s = File.Open(imageDir+"\\"+Path.GetFileName(textBox1.Text), FileMode.CreateNew))
using (StreamWriter sw = new StreamWriter(s))
{
sw.Write(textBox1.Text);
}
}
Second Approach: (Browser the File and Save Opens SaveDialog with Directory as Image Directory and File name as Previously selected File)
private void button2_Click(object sender, System.EventArgs e)
{
var assemblyPath = System.Reflection.Assembly.GetExecutingAssembly().Location;
var assemblyParentPath = Path.GetDirectoryName(assemblyPath);
var imageDir = Path.Combine(assemblyParentPath, "Image");
if (!Directory.Exists(imageDir))
Directory.CreateDirectory(imageDir);
SaveFileDialog f = new SaveFileDialog();
f.InitialDirectory = imageDir;
f.FileName = textBox1.Text;
if (f.ShowDialog() == DialogResult.OK)
{
using (Stream s = File.Open(imageDir + "\\" + Path.GetFileName(textBox1.Text), FileMode.CreateNew))
using (StreamWriter sw = new StreamWriter(s))
{
sw.Write(textBox1.Text);
}
}
}```
Does this code work for you?
private void button1_Click(object sender, EventArgs e)
{
var dlg = new OpenFileDialog();
dlg.Title = "Select Picture";
dlg.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
dlg.Filter = "Common Picture Files|*.gif;*.png;*.bmp;|All Files|*.*";
if (dlg.ShowDialog() == DialogResult.OK)
{
textBox1.Text = dlg.FileName;
}
}
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 want to print out a document using C#. I have two buttons. btnUpload uploads or selects a word file. btnPrinthave to send uploaded file to a printer. How can I do this? Now using:
private void btnUpload_Click(object sender, EventArgs e)
{
string fileName;
// Show the dialog and get result.
OpenFileDialog ofd = new OpenFileDialog();
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK) // Test result.
{
fileName = ofd.FileName;
var application = new Microsoft.Office.Interop.Word.Application();
//var document = application.Documents.Open(#"D:\ICT.docx");
var document = application.Documents.Open(#fileName);
}
}
private void btnPrint_Click(object sender, EventArgs e)
{
PrintDialog printDlg = new PrintDialog();
PrintDocument printDoc = new PrintDocument();
printDoc.DocumentName = "fileName";
printDlg.Document = printDoc;
printDlg.AllowSelection = true;
printDlg.AllowSomePages = true;
//Call ShowDialog
if (printDlg.ShowDialog() == DialogResult.OK)
printDoc.Print();
}
you need to hadle PrintPage event
Try This:
String content="";
private void btnUpload_Click(object sender, EventArgs e)
{
string fileName;
// Show the dialog and get result.
OpenFileDialog ofd = new OpenFileDialog();
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK) // Test result.
{
fileName = ofd.FileName;
var application = new Microsoft.Office.Interop.Word.Application();
//var document = application.Documents.Open(#"D:\ICT.docx");
//read all text into content
content=System.IO.File.ReadAllText(fileName);
//var document = application.Documents.Open(#fileName);
}
}
private void btnPrint_Click(object sender, EventArgs e)
{
PrintDialog printDlg = new PrintDialog();
PrintDocument printDoc = new PrintDocument();
printDoc.DocumentName = "fileName";
printDlg.Document = printDoc;
printDlg.AllowSelection = true;
printDlg.AllowSomePages = true;
//Call ShowDialog
if (printDlg.ShowDialog() == DialogResult.OK)
{
printDoc.PrintPage += new PrintPageEventHandler(pd_PrintPage);
printDoc.Print();
}
}
private void pd_PrintPage(object sender, PrintPageEventArgs ev)
{
ev.Graphics.DrawString(content,printFont , Brushes.Black,
ev.MarginBounds.Left, 0, new StringFormat());
}
I have a question about the opfiledialog function within c#. When i dont select a file with openfiledialog it put's a text automaticly in my textbox. That text will be "filedialog1". What can i do to fix this.
using System;
using System.Windows.Forms;
using System.IO;
namespace Flashloader
{
public partial class NewApplication : Form
{
private toepassinginifile _toepassinginifile;
private controllerinifile _controllerinifile;
//private controllerinifile _controlIniFile;
public NewApplication(toepassinginifile iniFile)
{
_controllerinifile = new controllerinifile();
_toepassinginifile = iniFile;
InitializeComponent();
controllerComboBox.DataSource = _controllerinifile.Controllers;
}
public bool Run()
{
var result = ShowDialog();
return result == System.Windows.Forms.DialogResult.OK;
}
private void button4_Click(object sender, EventArgs e)
{
this.Close();
}
private void button1_Click(object sender, EventArgs e)
{
openFileDialog1.Filter = "Srec Files (.a20; .a21; .a26; .a44)|*.a20; *.a21; *.a26; *.a44|All files (*.*)|*.*";
openFileDialog1.Title = ("Choose a file");
openFileDialog1.InitialDirectory = Path.Combine(Directory.GetCurrentDirectory());
openFileDialog1.RestoreDirectory = true;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
fileBox.Text = (System.IO.Path.GetFileName(openFileDialog1.FileName));
}
}
private void button3_Click(object sender, EventArgs e)
{
Toepassing toepassing = new Toepassing();
toepassing.Name = nameBox.Text;
toepassing.Controller = (Flashloader.Controller)controllerComboBox.SelectedItem;
toepassing.TabTip = descBox.Text;
toepassing.Lastfile = openFileDialog1.FileName;
fileBox.Text = openFileDialog1.FileName;
if (nameBox.Text == "")
MessageBox.Show("You haven't assigned a Name");
else if (controllerComboBox.Text == "")
MessageBox.Show("You haven't assigned a Controller");
else if (descBox.Text == "")
MessageBox.Show("You haven't assigned a Desciption");
else if (fileBox.Text == "")
MessageBox.Show("You haven't assigned a Applicationfile");
_toepassinginifile.ToePassingen.Add(toepassing);
_toepassinginifile.Save(toepassing);
MessageBox.Show("Save Succesfull");
DialogResult = DialogResult.OK;
this.Close();
}
private void button2_Click(object sender, EventArgs e)
{
var newcontroller = new Newcontroller(_controllerinifile);
newcontroller.ShowDialog();
controllerComboBox.DataSource = null;
controllerComboBox.DataSource = _controllerinifile.Controllers;
}
}
}
Thanks all for the help
private void button3_Click(object sender, EventArgs e)
{
toepassing.Lastfile = openFileDialog1.FileName;// Dont do this
fileBox.Text = openFileDialog1.FileName; //or this
Its unclear to me why you are holding onto an Open file dialog I would personally do the following
using(OpenFileDialog ofd = new OpenFileDialog())
{
if(ofd.ShowDialog() == DialogResult.OK)
{
classStringVariable = ofd.FileName;
fileBox.Text = ofd.FileName;
}
}
Then in button 3
toepassing.LastFile = classStringVariable ;
fileBox.Text = classStringVariable ;
When you use the Form Designer to add an OpenFileDialog control on you form, the designer assigns at the property FileName the value openFileDialog1.
I suppose you have set something as the initial value for the property FileName. Then in button_click3 you have no mean to check for the DialogResult and thus you get inconditionally this default back.
Fix it removing this default from the designer FileName property
Just add openFileDialog1.FileName= ""; before you show the dialog.
openFileDialog1.Filter = "Srec Files (.a20; .a21; .a26; .a44)|*.a20; *.a21; *.a26; *.a44|All files (*.*)|*.*";
openFileDialog1.Title = ("Choose a file");
openFileDialog1.InitialDirectory = Path.Combine(Directory.GetCurrentDirectory());
openFileDialog1.RestoreDirectory = true;
openFileDialog1.FileName = "";
if (openFileDialog1.ShowDialog() == DialogResult.OK && openFileDialog1.FileName != "")
{
fileBox.Text = (System.IO.Path.GetFileName(openFileDialog1.FileName));
}
In your button3_Click event you're checking for an empty string file name anyways, so they would get the correct error message and they wouldn't have some weird arbitrary default name show up when they open the dialog.