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
Related
I have a listbox which i can fill trough openfiledialog, which works but not the way i want it. I need 2 columns in my listbox 1 for the filepath and 1 for the fileName next to each other.
also i have another button which inserts all fileNames into the database, which works also but i also need the second column to update the path column in my database
Ive tried to make 2 columns 1 for the filename and 1 for the filepath, unfortunately i could only make 1 column work for my filename.
This is the code for filling in the listbox
private void btnOpenFiles_Click(object sender, RoutedEventArgs e)
{
lbfiles.Items.Clear();
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Multiselect = true;
openFileDialog.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
if (openFileDialog.ShowDialog() == true)
{
foreach (string filename in openFileDialog.FileNames)
lbfiles.Items.Add(System.IO.Path.GetFileName(filename));
}
}
this is the code for inserting into the database
private void BtnToDatabase_Click(object sender, RoutedEventArgs e)
{
bool dupe = false;
foreach (String string2 in lbfiles.Items.Cast<String>().ToList())
{
{
string cat1 = string2.Substring(0, string2.Length);
using (SqlConnection sqlCon = new SqlConnection(connectionString))
{
String query = "INSERT INTO tblBestanden2 (BestandNaam,toegewezen,Username,Status) VALUES (#BestandNaam, #toegewezen, #username, #Status)";
using (SqlCommand command = new SqlCommand(query, sqlCon))
{
command.Parameters.AddWithValue("#BestandNaam", cat1);
command.Parameters.AddWithValue("#toegewezen", "1");
command.Parameters.AddWithValue("#username", "");
command.Parameters.AddWithValue("#Status", "0");
sqlCon.Open();
int result = command.ExecuteNonQuery();
if (!dupe)
{
if (result == 0)
{
sqlCon.Close();
MessageBox.Show("error");
}
else
{
sqlCon.Close();
MessageBox.Show("toegevoegd");
}
dupe = true;
}
}
}
}
}
}
If there is any confusion about my question please tell me and i will try my best to elaborate
Create a class with two properties:
public class File
{
public string Name { get; set; }
public string Path { get; set; }
}
And instances of this one to the ListBox:
private void btnOpenFiles_Click(object sender, RoutedEventArgs e)
{
lbfiles.Items.Clear();
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Multiselect = true;
openFileDialog.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
if (openFileDialog.ShowDialog() == true)
{
foreach (string filename in openFileDialog.FileNames)
lbfiles.Items.Add(new File() { Name = System.IO.Path.GetFileName(filename), Path = filename });
}
}
You would then get the values by casting the items to File objects in your BtnToDatabase_Click event handler:
private void BtnToDatabase_Click(object sender, RoutedEventArgs e)
{
bool dupe = false;
foreach (File file in lbfiles.Items.OfType<File>())
{
string name = file.Name;
string path = file.Path;
...
}
}
In foreach statement, filepath is not included when this condition openFileDialog.ShowDialog() gets true, you are getting only filename. To get filepath, use System.IO.Path.GetFullPath(FileName);, you could get filepath for the filename
Hey there i started learning C# a few days ago and I'm trying to make a program that copies and pastes files (and replaces if needed) to a selected directory but I don't know how to get the directory and file paths from the openfiledialog and folderbrowserdialog
what am I doing wrong?
Here's the code:
namespace filereplacer
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void direc_Click(object sender, EventArgs e)
{
string folderPath = "";
FolderBrowserDialog directchoosedlg = new FolderBrowserDialog();
if (directchoosedlg.ShowDialog() == DialogResult.OK)
{
folderPath = directchoosedlg.SelectedPath;
}
}
private void choof_Click(object sender, EventArgs e)
{
OpenFileDialog choofdlog = new OpenFileDialog();
choofdlog.Filter = "All Files (*.*)|*.*";
choofdlog.FilterIndex = 1;
choofdlog.Multiselect = true;
choofdlog.ShowDialog();
}
private void replacebtn_Click(object sender, EventArgs e)
{
// This is where i'm having trouble
}
public static void ReplaceFile(string FileToMoveAndDelete, string FileToReplace, string BackupOfFileToReplace)
{
File.Replace(FileToMoveAndDelete, FileToReplace, BackupOfFileToReplace, false);
}
}
For OpenFileDialog:
OpenFileDialog choofdlog = new OpenFileDialog();
choofdlog.Filter = "All Files (*.*)|*.*";
choofdlog.FilterIndex = 1;
choofdlog.Multiselect = true;
if (choofdlog.ShowDialog() == DialogResult.OK)
{
string sFileName = choofdlog.FileName;
string[] arrAllFiles = choofdlog.FileNames; //used when Multiselect = true
}
For FolderBrowserDialog:
FolderBrowserDialog fbd = new FolderBrowserDialog();
fbd.Description = "Custom Description";
if (fbd.ShowDialog() == DialogResult.OK)
{
string sSelectedPath = fbd.SelectedPath;
}
To access selected folder and selected file name you can declare both string at class level.
namespace filereplacer
{
public partial class Form1 : Form
{
string sSelectedFile;
string sSelectedFolder;
public Form1()
{
InitializeComponent();
}
private void direc_Click(object sender, EventArgs e)
{
FolderBrowserDialog fbd = new FolderBrowserDialog();
//fbd.Description = "Custom Description"; //not mandatory
if (fbd.ShowDialog() == DialogResult.OK)
sSelectedFolder = fbd.SelectedPath;
else
sSelectedFolder = string.Empty;
}
private void choof_Click(object sender, EventArgs e)
{
OpenFileDialog choofdlog = new OpenFileDialog();
choofdlog.Filter = "All Files (*.*)|*.*";
choofdlog.FilterIndex = 1;
choofdlog.Multiselect = true;
if (choofdlog.ShowDialog() == DialogResult.OK)
sSelectedFile = choofdlog.FileName;
else
sSelectedFile = string.Empty;
}
private void replacebtn_Click(object sender, EventArgs e)
{
if(sSelectedFolder != string.Empty && sSelectedFile != string.Empty)
{
//use selected folder path and file path
}
}
....
}
NOTE:
As you have kept choofdlog.Multiselect=true;, that means in the OpenFileDialog() you are able to select multiple files (by pressing ctrl key and left mouse click for selection).
In that case you could get all selected files in string[]:
At Class Level:
string[] arrAllFiles;
Locate this line (when Multiselect=true this line gives first file only):
sSelectedFile = choofdlog.FileName;
To get all files use this:
arrAllFiles = choofdlog.FileNames; //this line gives array of all selected files
Use the Path class from System.IO. It contains useful calls for manipulating file paths, including GetDirectoryName which does what you want, returning the directory portion of the file path.
Usage is simple.
string directoryPath = System.IO.Path.GetDirectoryName(choofdlog.FileName);
you can store the Path into string variable like
string s = choofdlog.FileName;
To get the full file path of a selected file or files, then you need to use FileName property for one file or FileNames property for multiple files.
var file = choofdlog.FileName; // for one file
or for multiple files
var files = choofdlog.FileNames; // for multiple files.
To get the directory of the file, you can use Path.GetDirectoryName
Here is Jon Keet's answer to a similar question about getting directories from path
Create this class as Extension:
public static class Extensiones
{
public static string FolderName(this OpenFileDialog ofd)
{
string resp = "";
resp = ofd.FileName.Substring(0, 3);
var final = ofd.FileName.Substring(3);
var info = final.Split('\\');
for (int i = 0; i < info.Length - 1; i++)
{
resp += info[i] + "\\";
}
return resp;
}
}
Then, you could use in this way:
//ofdSource is an OpenFileDialog
if (ofdSource.ShowDialog(this) == DialogResult.OK)
{
MessageBox.Show(ofdSource.FolderName());
}
Your choofdlog holds a FileName and FileNames (for multi-selection) containing the file paths, after the ShowDialog() returns.
A primitive quick fix that works.
If you only use OpenFileDialog, you can capture the FileName, SafeFileName, then subtract to get folder path:
exampleFileName = ofd.SafeFileName;
exampleFileNameFull = ofd.FileName;
exampleFileNameFolder = ofd.FileNameFull.Replace(ofd.FileName, "");
I am sorry if i am late to reply here but i just thought i should throw in a much simpler solution for the OpenDialog.
OpenDialog ofd = new OpenDialog();
var fullPathIncludingFileName = ofd.Filename; //returns the full path including the filename
var fullPathExcludingFileName = ofd.Filename.Replace(ofd.SafeFileName, "");//will remove the filename from the full path
I have not yet used a FolderBrowserDialog before so i will trust my fellow coders's take on this. I hope this helps.
String fn = openFileDialog1.SafeFileName;
String path = openFileDialog1.FileName.ToString().Replace(fn, "");
I couldn't find any method to add in the if statement to read a text file. Here is the code;
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)
{
}
I just wanna get whole text froma text file that I choose from this OpenFolderDialog window.
string text = System.IO.File.ReadAllText(BrowseFile1.FileName);
Another possibility is using a StreamReader:
http://msdn.microsoft.com/en-us/library/db5x7c0d(v=vs.110).aspx
Just Change the file locatations through BrowseFile1.FileName.
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.
I want to read a text file which contains more than one paragraph separated by new lines. How to read every paragraph alone in RichTextBox and how to transfer to the next paragraph by button next and back to the first paragraph by button previous designed in the form. My code
private void LoadFile_Click(object sender, EventArgs e)
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
dialog.Title = "Select a text file";
dialog.ShowDialog();
if (dialog.FileName != "")
{
System.IO.StreamReader reader = new System.IO.StreamReader(dialog.FileName);
string Text = reader.ReadToEnd();
reader.Close();
this.Input.TextChanged -= new System.EventHandler(this.Input_TextChanged);
Input.Clear();
Input.Text = Text;
}
}
Use this code.
var text = File.ReadAllText(inputFilePath);
var paragraphs = text .Split('\n');
paragraphs will be an array of strings containing all the paragraphs.
Use String.split() to split it at '\n'.
Afterwards iterate through the array on the Button next.
private string[] paragraphs;
private int index = 0;
private void LoadFile_Click(object sender, EventArgs e)
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Filter =
"txt files (*.txt)|*.txt|All files (*.*)|*.*";
dialog.Title = "Select a text file";
dialog.ShowDialog();
if (dialog.FileName != "")
{
System.IO.StreamReader reader = new System.IO.StreamReader(dialog.FileName);
string Text = reader.ReadToEnd();
reader.Close();
this.Input.TextChanged -= new System.EventHandler(this.Input_TextChanged);
Input.Clear();
paragraphs = Text.Split('\n');
index = 0;
Input.Text = paragraphs[index];
}
}
private void Next_Click(object sender, EventArgs e)
{
index++;
Input.Text = paragraphs[index];
}
(I know this might not be the most elegant solution but it should give an idea on what to do.)