private void button1_Click(object sender, EventArgs e)
{
textBox1.Text = Clipboard.GetData.ToString();
}
I pressed Ctrl+C on a file, not a text. I want set TextBox.Text or a string the location of the file. suppose c:\myfile.abc in Clipboard. I want set text equal to the location/path present in the clipboard.
if (Clipboard.ContainsFileDropList()) // If Clipboard has one or more files
{
var files = Clipboard.GetFileDropList().Cast<string>().ToArray(); // Get all files from clipboard
if (files != null)
{
if (files.Length >= 1)
{
string filepath = files[0]; // Get first file from clipboard as a file path
textBox1.Text = filepath;
}
}
}
Related
I created a File Searcher ( I provide the directory of folders in Open Directory button and i choose Extension if (txt or png or html etc...) and in term i write the word i want to search for it like
Example.txt
index.html,
etc...
and after that I click Search For Files and I get Result In the listBox1
After that to Search for a specific word I write in Term The Word To Search it inside a selected txt file from the listbox1 but for txt Files I want to Search a specific Word in all txt files without selecting any file from listbox1 and I want a code to show how many files I get in the result (listbox1) in number and how to open a specific file from listbox1 just with clicking it 2 times and how to copy a file or select or remove from listbox1
Questions :
how to change the code of this (Search For Word In Specific File) in a code that can (Search For Word In All Files And Give me Results)?
How to open file that is shown in the listbox?
How to copy file inside the file in the listbox?
How to copy a file or select or remove from listbox1 ?
How to open a specific file from listbox1 just with clicking it 2 times ?
What is the code to show how many files i get in the result (listbox1) in number ?
The Code :
private void FileFound(string path)
{
listBox1.BeginInvoke((Action)delegate ()
{
listBox1.Items.Add(path);
});
}
private void WorkerCompleted(object sender, RunWorkerCompletedEventArgs args)
{
MessageBox.Show("Done");
}
private void WorkInBackground(object sender, DoWorkEventArgs args)
{
searcher.Search();
}
private void button1_Click(object sender, EventArgs e)
{
if(comboBox1.SelectedIndex == -1 || string.IsNullOrEmpty(textBox1.Text)|| string.IsNullOrEmpty(textBox2.Text) )
{
MessageBox.Show("Please Select An Extension Or Select A Directory Or Fill a word");
return;
}
listBox1.Items.Clear();
this.searcher.Term = textBox2.Text;
this.searcher.Dir = textBox1.Text;
this.searcher.Ext = comboBox1.SelectedItem.ToString();
bgWorker.RunWorkerAsync();
}
private void button2_Click(object sender, EventArgs e)
{
CommonOpenFileDialog dialog = new CommonOpenFileDialog();
dialog.IsFolderPicker = true;
dialog.RestoreDirectory = true;
if(dialog.ShowDialog() == CommonFileDialogResult.Ok)
{
textBox1.Text = dialog.FileName;
}
}
private void button3_Click(object sender, EventArgs e)
{
try
{
if (!listBox1.SelectedItem.ToString().Contains(".txt") )
{
MessageBox.Show("Please Select Text File");
return;
}
if (string.IsNullOrEmpty(textBox2.Text))
{
MessageBox.Show("Please type a Term");
return;
}
this.searcher.Term = textBox2.Text;
this.searcher.Dir = listBox1.SelectedItem.ToString();
string words = File.ReadAllText(listBox1.SelectedItem.ToString());
if (words.ToLower().Contains(textBox2.Text.ToLower()))
{
MessageBox.Show("word Founded");
}
else
{
MessageBox.Show("No Such a Word");
}
}
catch (Exception)
{
MessageBox.Show("Please Select A File");
}
//bgWorker.RunWorkerAsync();
}
}
In my company it is common to name files in the following manner: 210808_Filename.extension
Unfortunately both of these ways to get the filename failed: Path.GetFileName() and OpenFileDialog.SafeFileName. In the path itself the underscores exist, but in the filename they get removed.
private void btnOpenFile_Click(object sender, RoutedEventArgs e)
{
string strCheck = "";
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.ShowDialog();
strConfigPath1 = openFileDialog1.FileName;
if (strConfigPath1.Length > 6)
{
strCheck = strConfigPath1.Substring(strConfigPath1.Length - 6);
}
if (strConfigPath1 == "" || strCheck != ".gcode")
{
MessageBox.Show("Selected file has to be a GCode file.");
}
else
{
lblSelectedDocument.Content = System.IO.Path.GetFileName(string);
}
}
I know it may not be a well programmed code due to the fact I am bloody new to programming. Sorry for that.
Here's a straightforward way to set the contents of the label, based on the file that the user selects:
private void btnOpenFile_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
if (openFileDialog.ShowDialog() == true)
{
string chosenFilename = openFileDialog.FileName;
if (Path.GetExtension(chosenFilename).ToLower() == ".gcode")
{
lblSelectedDocument.Content = "Valid file. You selected " + chosenFilename;
}
else
{
lblSelectedDocument.Content = "Invalid file - not a .GCODE file. You selected " + chosenFilename;
}
}
else
{
lblSelectedDocument.Content = "You did not select a file.";
}
}
If the user doesn't select a file, we just set the label to be You did not select a file.
If the user did select a file, we check if the file extension is our intended extension. The check is case-insensitive, so .GCODE, .GcOdE, .gcode (etc) will all work. If the user selected a gcode file, the label says the filename is valid and shows the filename.
If the file extension doesn't match, the user must have selected an invalid file. When this occurs we tell them the filename is invalid and show the filename.
Not sure how to implement this, i am not using SaveFileDialog which i have seen uses OverWritePrompt = true cant seem to get that to work for me.
I am using WPF.
The structure:-
I have a textBox called filePathBox - This contains a file path used from opening an: OpenFileDialog
private void fileBrowser_Click(object sender, RoutedEventArgs e)
{
//Firstly creating the OpenFileDialog
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
//Setting the filter for the file extension of the files as well as the default extension
dlg.DefaultExt = ".txt";
dlg.Filter = "All Files|*.*";
//Display the dialog box by calling the ShowDialog method
Nullable<bool> result = dlg.ShowDialog();
//Grab the file you selected and display it in filePathBox
if (result == true)
{
//Open The document
string filename = dlg.FileName;
filePathBox.Text = filename;
}
}
You can then click a button and the .txt file displays in a textBox called textResult
private void helpfulNotes_Click(object sender, RoutedEventArgs e)
{
if (File.Exists(filePathBox.Text) && System.IO.Path.GetExtension(filePathBox.Text).ToLower() == ".txt")
{
textResult.Text = File.ReadAllText(filePathBox.Text);
}
if (string.IsNullOrWhiteSpace(filePathBox.Text))
{
MessageBox.Show("Please choose a file by clicking on the folder Icon :(");
}
}
Once you have made changes to that text in 'textResult' i have a button to save the text back to the file path that was originally loaded using the OpenFileDialog
private void saveText_Click(object sender, RoutedEventArgs e)
{
if (string.IsNullOrEmpty(textResult.Text))
{
saveText.IsEnabled = false;
MessageBox.Show("No Text to save!");
}
else
{
saveText.IsEnabled = true;
string test = textResult.Text;
System.IO.File.WriteAllText(filePathBox.Text, test);
}
//fileSaveIcon.Visibility = Visibility.Visible;
//fileChangedIcon.Visibility = Visibility.Hidden;
}
At the moment it all saves fine, only it doesn't prompt the user saying are you sure you want to overwrite the file.
At the moment i could
load a file for the purpose of this named TestNote.txt into the
filePathBox
Type some text in textResult before even clicking to display the
file
Click save and it would just overwrite TestNote.txt with the text i
just entered without even warning me
Hopefully i have explained this adequately and provided all the code you need
Just add a messagebox to show your alert message before writing to the text file.
private void saveText_Click(object sender, RoutedEventArgs e)
{
if (string.IsNullOrEmpty(textResult.Text))
{
saveText.IsEnabled = false;
MessageBox.Show("No Text to save!");
}
else
{
if(MessageBox.Show("are you sure you want to overwrite the file.", "Alert", MessageBoxButtons.YesNo)==DialogResult.Yes)
{
saveText.IsEnabled = true;
string test = textResult.Text;
System.IO.File.WriteAllText(filePathBox.Text, test);
}
}
//fileSaveIcon.Visibility = Visibility.Visible;
//fileChangedIcon.Visibility = Visibility.Hidden;
}
Well, OverWritePrompt is a SaveFileDialog property, which you're not using: you're always using File.WriteAllText(), which always overwrites the target file.
You want to provide a Save function that saves an earlier opened file without prompt, a Save As function that prompts the user for a new filename and also call Save As when saving a new file.
This is implemented like this, pseudo:
private string _currentlyOpenedFile;
public void FileOpen_Click(...)
{
var openFileDialog = new ...OpenFileDialog();
if (openFileDialog.ShowDialog())
{
// Save the filename when opening a file.
_currentlyOpenedFile = openFileDialog.FileName;
}
}
public void FileNew_Click(...)
{
// Clear the filename when closing a file or making a new file.
_currentlyOpenedFile = null;
}
public void FileSave_Click(...)
{
if (_currentlyOpenedFile == null)
{
// New file, treat as SaveAs
FileSaveAs_Click();
return;
}
}
public void FileSaveAs_Click(...)
{
var saveFileDialog = new ...SaveFileDialog();
if (openFileDialog.ShowDialog())
{
// Write the file.
File.WriteAllText(text, openFileDialog.FileName);
// Save the filename after writing the file.
_currentlyOpenedFile = openFileDialog.FileName;
}
}
Here you'll be leveraging the SaveFileDialog's functionality which prompts the user whether they want to overwrite an already existing file.
I opened a directory and I read some files in that directory amd made some changes, now I want to save the changes with the same file names at F:\BI\Out\ and keep the original files.
when I added these two lines
var outFilePath = #"F:\BI\Out\" + Path.GetFileName(file);
File.WriteAllText(outFilePath, text);
I was able to save the files under the new folder\Out,
but when I opened them I found that only one file is changed correctly and all the other files the old words are replace by blank space not by the new words.
Can anyone help me Thanks
string text = "";
string[] files;
private void Form1_Load(object sender, EventArgs e)
{
try
{
files = Directory.GetFiles(#"F:\BI\In\", "*.*", SearchOption.AllDirectories);
}
catch (IOException ex)
{
MessageBox.Show(ex.Message);
this.Close();
}
}
private void btnUpdate_Click(object sender, EventArgs e)
{
if (txtEtlPath.Text == "")
{
MessageBox.Show("Please Enter path");
txtEtlPath.Focus();
}
else
{
foreach (string file in files)
{
if (System.IO.File.Exists(file))
{
text = File.ReadAllText(file);
text = text.Replace("Company_Address", txtCompanyAddress.Text + "_BI");
text = text.Replace("Company_Name", txtCompanyName.Text.Trim() + "_BIDW");
text = text.Replace("C:\\BIfolder",cboDrive.Text + txtEtlPath.Text.Trim());
var outFilePath = #"F:\BI\Out\" + Path.GetFileName(file);
File.WriteAllText(outFilePath, text);
}
Within your foreach () loop:
If you want the subfolder structure of the files found, do a replace on the filepath:
var outFilePath = file.Replace(#"F:\BI\In\", #"F:\BI\Out\");
You will need to create the subfolder before you can write the changed file:
new FileInfo(outFilePath)).Directory.Create();
If you don't want the subfolders, you can write directly into the top folder:
var outFilePath = #"F:\BI\Out\" + Path.GetFileName(file);
Writing is simple, just keep in mind there is an optional encoding parameter:
File.WriteAllText(outFilePath, text);
I need to get the path of a file which is in a specific directory.The user selects a csv file from a OpenFileDialog. If the csv file has field that ends at .txt then take the path of that file and put it in a pathfile variable. The new file has to be placed, by the user, in the same directory as the csv file.
EDIT: How do I put the path of the file in a variable ?
EDIT2: The file could be placed everywhere, for example: C://george.csv. So I want to take a txt from the directory c:// .Or if the file is here: C://Documents/anna.csv. The text has to be C://Documents/textfile.txt.
EDIT3: The csv file that the user has opened is at c://Documents/gonow.csv
The file gonow.csv is : one, two, tree, four, textfile.txt, five, six, seven.
When a field has extension .txt then the program has to go and cath the path. In this case the path is c://Documents/textfile.txt.
private void button3_Click(object sender, EventArgs e)
{
string filename = "";
DialogResult result = openFileDialog2.ShowDialog();
if (result == DialogResult.OK)
{
filename = openFileDialog2.FileName;
textBox3.Text = filename;
System.IO.StreamReader file2 = new System.IO.StreamReader(textBox3.Text);
}
}
private void button2_Click(object sender, EventArgs e)
{
if (Path.GetExtension(colB[j]) == ".csv")
textBox2.Text += " comma separated, in line " + j + "" + Environment.NewLine;
}
Try
string path = Path.GetDirectoryName(filename);
EDITED according to your EDIT3:
Use this function to open your csv file and get new complete filename.
private string GetFilename(string csvFilename)
{
string path = Path.GetDirectoryName(csvFilename);
string[] lines = File.ReadAllLines(csvFilename);
foreach (string line in lines)
{
string[] items = line.Split(',');
string txt = items.First(item => item.ToLower().Trim().EndsWith(".txt"));
if (!String.IsNullOrEmpty(txt))
return Path.Combine(path, txt);
}
return "";
}
iF you need to put the txt file (the generated file) in the same folder as that of the CSV file, you can store the path of the CSV file and create the txt file in theat folder.
To do this you may like to have a variable like this:
private void button3_Click(object sender, EventArgs e)
{
string filename = "";
string FolderPath;
DialogResult result = openFileDialog2.ShowDialog();
if (result == DialogResult.OK)
{
filename = openFileDialog2.FileName;
FolderPath = Path.GetDirectoryName(filename);
textBox3.Text = filename;
System.IO.StreamReader file2 = new System.IO.StreamReader(textBox3.Text);
}
}
private void button2_Click(object sender, EventArgs e)
{
if (Path.GetExtension(colB[j]) == ".csv")
textBox2.Text += " comma separated, in line " + j + "" + Environment.NewLine;
}
The FolderPAth variable holds the path to the folder. You can create the txt file in this folder. This means that the txt file is in the same folder as of the csv file. If you need to access this in a different method, you may declare it in relevant scope.