When executing the following code, I would expect a warning pop up dialog, which will ask if I am sure I would like to overwrite the file, but no pop up appears. Does anyone know a simple way to implement it? Without having to create my own custom window
XAML:
<Grid>
<TextBox x:Name="name" Text="hi" />
<Button x:Name="create_File" Click="create_File_Click" Content="make the notepad" Width="auto"/>
</Grid>
c#:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
public void createFile()
{
string text_line = string.Empty;
string exportfile_name = "C:\\" + name.Text + ".txt";
System.IO.StreamWriter objExport;
objExport = new System.IO.StreamWriter(exportfile_name);
string[] TestLines = new string[2];
TestLines[0] = "****TEST*****";
TestLines[1] = "successful";
for (int i = 0; i < 2; i++)
{
text_line = text_line + TestLines[i] + "\r\n";
objExport.WriteLine(TestLines[i]);
}
objExport.Close();
MessageBox.Show("Wrote File");
}
private void create_File_Click(object sender, RoutedEventArgs e)
{
createFile();
}
}
UPDATE
I was not using SaveFileDialog, Now I am and it works just how I would expect it too... thanks for the answers, here is what I have now:
public void createFile()
{
string text_line = string.Empty;
string export_filename = name.Text;
Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
dlg.FileName = export_filename; // Default file name
dlg.DefaultExt = ".text"; // Default file extension
dlg.Filter = "Text documents (.txt)|*.txt"; // Filter files by extension
// Show save file dialog box
Nullable<bool> result = dlg.ShowDialog();
// save file
System.IO.StreamWriter objExport;
objExport = new System.IO.StreamWriter(dlg.FileName);
string[] TestLines = new string[2];
TestLines[0] = "****TEST*****";
TestLines[1] = "successful";
for (int i = 0; i < 2; i++)
{
text_line = text_line + TestLines[i] + "\r\n";
objExport.WriteLine(TestLines[i]);
}
objExport.Close();
}
private void create_File_Click(object sender, RoutedEventArgs e)
{
createFile();
}
}
Asking the user whether the file should be overwritten is usually done when the file path is chosen, not when the file is actually written.
If you let the user choose the path using a SaveFileDialog, the OverwritePrompt property is set to true by default, resulting in the confirmation dialog you desire.
If you don't want to use the SaveFileDialog, you can use a MessageBox with the MessageBoxButtons.YesNo option.
1) Check if the File exists (File.Exists)
2) If it does, display a MessageBox (MessageBox.Show) with yes and no options.
3) Check if the user clicked yes, and only then execute the rest of your code
DialogResult dialogResult = File.Exists(exportfile_name)
? MessageBox.Show(null, "Sure?", "Some Title", MessageBoxButtons.YesNo)
: DialogResult.Yes;
if (dialogResult == DialogResult.Yes)
{
// save file
}
Related
I'm been wondering is there a way to save a file in specific's folder in C#?
The only method that I know is 'SaveFileDialog' but the problems is I want to save files
in folder without showing saveFilesDialog's Box.
saveFilesDialog's Box : is a box that prompts you to Click 'YES' or 'CANCEL'.
Code samples
-In form1
public Form1()
{
InitializeComponent();
}
private string Path =#"D:\Files"; //locaction i wanna stores all the files in
private int i = 0;
private button1_Click(object sender,EventArgs e)
{
i++;
SaveDialogFile save = new SaveDialogFile();
if(Save.
if (save.ShowDialog() != DialogResult.OK)return; //Prompt's Dialog will show
save.Filter = "File Text(*.txt)|*.txt";
save.InitialDirectory = Path;
save.FileName = "txt"+i.ToString();
//Goal : i want 'save.FileName' store in 'Path' without Click 'OK' or Show Prompt Dialog's box
}
Expect Result
[1]: https://i.stack.imgur.com/9JqWO.png
Anyone can help me? I kinda stuck rn :)
This is my full code it's hard to read but you'll get the point
public partial class convertMp3ToWav : Form
{
public convertMp3ToWav()
{
InitializeComponent();
}
BackgroundWorker bw;
string withoutEx;
List<string> song_lists = new List<string>();
private void button1_Click(object sender, EventArgs e)
{
bw = new BackgroundWorker();
bw.DoWork += (obj, ae) => newThread();
bw.RunWorkerAsync();
}
void newThread()
{
Thread th = new Thread
((ThreadStart)(() =>
{
file();
}));
th.SetApartmentState(ApartmentState.STA);
th.Start();
th.Join();
}
void file()
{
string path = #"D:\musics\wav";
Directory.CreateDirectory(path);
FolderBrowserDialog f = new FolderBrowserDialog();
f.ShowDialog();
string[] lists = Directory.GetFiles(f.SelectedPath, "*.*", SearchOption.AllDirectories);
foreach (string list in lists)
{
if (Path.GetExtension(list) == ".mp3")
{
string fn = Path.GetFullPath(list);
withoutEx = Path.GetFileNameWithoutExtension(fn);
song_lists.Add(fn);
Console.WriteLine(withoutEx);
SaveFileDialog save = new SaveFileDialog();
save.Filter = "Wav FIle (*.wav)|*.wav;";
//save.FileName = song_lists[0];
save.FileName = withoutEx;
save.InitialDirectory = path;
if (save.ShowDialog() == DialogResult.OK)
{
using (Mp3FileReader mp3 = new Mp3FileReader(fn))
{
using (WaveStream pcm = WaveFormatConversionStream.CreatePcmStream(mp3))
{
WaveFileWriter.CreateWaveFile(save.FileName, pcm);
}
}
}
}
}
}
}
this code's work pretty well!! but i need to click 'OK' everytime!!
so is there anyway to save file without click 'OK' everytime!!
Conceptually the only thing SaveFileDialog is doing, if you merely click OK when it shows, is changing the file extension*. Use Path.ChangeExtension instead
var pathToSaveWavTo = Path.ChangeExtension(pathToMp3, "wav");
The wav will be saved alongside the mp3. If you want to save it elsewhere, use Path.Combine to build a new path e.g.
pathToSaveWavTo = Path.Combine(#"c:\temp", Path.GetFileName(pathToSaveWavTo));
*I say this because giving it a filter of *.WAV and a filename xxx without the mp3 extension will cause it to give you a filename of xxx.wav when you only click OK, thus xxx.mp3 -> xxx.wav
I have tesseract installed and I am using button click to set location of tesseract.exe file. I am also using another button click to set the location of the image file. Now I want the third button click to process the image with tesseract as I have stored their respective locations.
I am using some basic crude approach but it suits me.
My code is like:
private void B8_Click(object sender, EventArgs e)
{
q = z + "\\" + "output.txt";
if (k != null)
{
Process pr = new Process();
pr.StartInfo.FileName = j;
pr.StartInfo.Arguments = k + " " + q;
pr.Start();
pr.WaitForExit();
}
else
{
MessageBox.Show("No Image File Selected.");
}
var filetext = File.ReadAllText(q);
tb5.Text = filetext;
//File.Delete(q);
}
private void B10_Click(object sender, EventArgs e)
{
openFileDialog1 = new OpenFileDialog();
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
j = "\"" + openFileDialog1.FileName + "\"";
MessageBox.Show("Tesseract Location Set: " + j);
}
}
private void B9_Click(object sender, EventArgs e)
{
openFileDialog1 = new OpenFileDialog();
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
k = "\"" + openFileDialog1.FileName + "\"";
MessageBox.Show("Image File Location Set: " + k);
}
}
My 3-button click story so far:
I have successfully run the code with 1-button to set the tesseract.exe path, 2-button to set the image path, but the 3-button (see B-8) has an issue.
It extracts the text and stores into an "output.txt" file. But, I am not able to import this text into my textbox tb5 and then destroy this file.
The error I am getting is Exception thrown: 'System.IO.FileNotFoundException' in mscorlib.dll
An unhandled exception of type 'System.IO.FileNotFoundException' occurred in mscorlib.dll
Could not find file 'C:\Users\ambij\Desktop\try\output.txt'.
I don't understand this but there is actually output.txt file residing in the folder.
The following is for Tesseract 3.05.02 - May work in a later version
private void RunIt()
{
string tessDataPath = yourTessDataPath; // Your Tesseract Location Set
string imagePath = yourImagePath; // The Image File Location
string theTextFromTheImage = DoOCR(yourTessDataPath, yourImagePath);
// Some formatting may be required - OCR isn't perfect
MessageBox.Show(theTextFromTheImage);
}
private string DoOCR(string tessdataPath, string filePath)
{
string returnText = "";
using (var engine = new TesseractEngine(tessdataPath, "eng", EngineMode.Default))
{
// engine.SetVariable("tessedit_char_whitelist", "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"); // Only regular letters
string theVersion = engine.Version; // Optional, but useful
using (var img = Pix.LoadFromFile(filePath))
{
using (var page = engine.Process(img))
{
returnText = page.GetText();
}
}
}
return returnText;
}
Currently having an issue when saving a merged word. doc to a specific location using a filebrowser dialog
// input destintion
private string[] sourceFiles;
private void browseButton_Click(object sender, EventArgs e)
{
FolderBrowserDialog diagBrowser = new FolderBrowserDialog();
diagBrowser.Description = "Select a folder which contains files needing combined...";
// Default folder, altered when the user selects folder of choice
string selectedFolder = #"";
diagBrowser.SelectedPath = selectedFolder;
// initial file path display
folderPath.Text = diagBrowser.SelectedPath;
if (DialogResult.OK == diagBrowser.ShowDialog())
{
// Grab the folder that was chosen
selectedFolder = diagBrowser.SelectedPath;
folderPath.Text = diagBrowser.SelectedPath;
sourceFiles = Directory.GetFiles(selectedFolder, "*.doc");
}
}
// output destintion
private string[] sourceFileOutput;
private void browseButtonOut_Click(object sender, EventArgs e)
{
FolderBrowserDialog diagBrowserOutput = new FolderBrowserDialog();
diagBrowserOutput.Description = "Select a folder location to save the document...";
// Default folder, altered when the user selects folder of choice
string outputFolder = #"";
diagBrowserOutput.SelectedPath = outputFolder;
// output file path display
outputPath.Text = diagBrowserOutput.SelectedPath;
if (DialogResult.OK == diagBrowserOutput.ShowDialog())
{
outputFolder = diagBrowserOutput.SelectedPath;
outputPath.Text = diagBrowserOutput.SelectedPath;
sourceFileOutput = Directory.GetFiles(outputFolder);
}
}
private void combineButton_Click(object sender, EventArgs e)
{
if (sourceFiles != null && sourceFiles.Length > 0)
{
string outputFileName = (sourceFileOutput + "Combined.docx");
MsWord.Merge(sourceFiles, outputFileName, true);
// Message displaying how many files are combined.
MessageBox.Show("A total of " + sourceFiles.Length.ToString() + " documents have been merged", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
// Message displaying error.
MessageBox.Show("Please a select a relevant folder with documents to combine", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
instead of getting the 'combined.docx' in the location chosen, i instead get a file called 'System.String[]Combined' saved on the desktop. Obviously there is something clashing regarding the name and the user selected file path.
i currently have the input folder options working however the output + file name doesn't seem to be working correctly.
any suggestions or help would be greatly appreciated, thank you.
string outputFileName = (sourceFileOutput + "Combined.docx");
This should probably read
string outputFileName = selectedFolder + "Combined.docx";
That said, please use Path.Combine to combine two parts of a path.
got the program to use the 'selected' destination.
// output destintion
string outputFolder = #"";
private void browseButtonOut_Click(object sender, EventArgs e)
{
FolderBrowserDialog diagBrowserOutput = new FolderBrowserDialog();
diagBrowserOutput.Description = "Select a folder location to save the document...";
// Default folder, altered when the user selects folder of choice
diagBrowserOutput.SelectedPath = outputFolder;
// output file path display
outputPath.Text = diagBrowserOutput.SelectedPath;
if (DialogResult.OK == diagBrowserOutput.ShowDialog())
{
outputFolder = diagBrowserOutput.SelectedPath;
outputPath.Text = diagBrowserOutput.SelectedPath;
}
}
private void combineButton_Click(object sender, EventArgs e)
{
if (sourceFiles != null && sourceFiles.Length > 0)
{
string folderFolder = outputFolder;
string outputFile = "Combined.docx";
string outputFileName = Path.Combine(folderFolder, outputFile);
MsWord.Merge(sourceFiles, outputFileName, true);
// Message displaying how many files are combined.
MessageBox.Show("A total of " + sourceFiles.Length.ToString() + " documents have been merged", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
i used the path.combine as suggested, as played around with the variables i had used.
I'm trying to open a file dialog and open the files inside a folder into different rich text boxes? but i'm not sure what else I would need to add? could you please help out a new blood.
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
richTextBox1.Text = File.ReadAllText(openFileDialog1.FileName);
tabPage1.Text = openFileDialog1.SafeFileName;
}
If you want to allow your user to select a folder and then open the first 5 files present in that folder each one in a different richtextbox then you don't need the OpenFileDialog, but the FolderBrowserDialog
// First prepare two list with the richtextboxes and the tabpages
List<RichTextBox> myBoxes = new List<RichTextBox>()
{ richTextBox1, richTextBox2, richTextBox3, richTextBox4, richTextBox5 };
List<TabPage> myPages = new List<TabPage>()
{ tabPage1, tabPage2, tabPage3, tabPage4, tabPage5};
// Now open the folderbrowser dialog
// (see link above for some of its properties)
FolderBrowserDialog fbd = new FolderBrowserDialog();
if(fbd.ShowDialog() == DialogResult.OK)
{
int i = 0;
foreach(string file in Directory.GetFiles(fbd.SelectedPath))
{
myBoxes[i].Text = File.ReadAllText(file);
myPages[i].Text = Path.GetFileName(file);
i++;
// Added a warning if the folder contains more than 5 files
if(i >= 5)
{
MessageBox.Show("Too many files in folder, only 5 loaded");
break;
}
}
}
OpenFileDialog is to open but one file by default. Try to change its MultiSelect property to true. Something like this will do:
openFileDialog1.Multiselect = true;
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK) {
for (int i = 0; i < openFileDialog1.FileNames.Length; ++i) {
RichTextBox rtb = Controls.Cast<Control>().Single(x => x.Name == "richTextBox" + (i + 1).ToString()) as RichTextBox;
rtb.Text = File.ReadAllText(openFileDialog1.FileNames[i]);
}
tabPage1.Text = openFileDialog1.SafeFileName; //again, I wonder what you want to do with this. If needed be, consider to update this dynamically too
}
Old answer:
openFileDialog1.Multiselect = true; //important: set this to true
richTextBox1.Text = ""; //and you may want to reset this every time
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK) {
foreach(var filename in openFileDialog1.FileNames) //get file names here
richTextBox1.Text += File.ReadAllText(filename); //you may want to add enter per file
tabPage1.Text = openFileDialog1.SafeFileName; //but I wonder what you want to do with this....?
}
I can't seem to get access to the file I'm working with in the program I'm writing. I'm not sure how exactly to work this since I want my program to open a file of your choice, which it does, then I want it to be able to take in info into an arrary, which it does, then from there, write that information from the array to the file you opened up. When I try some code to start working on it it tells me, "The process cannot access the file 'file' because it is being used by another process." Here is what I have so far. Please let me know. Thank you. The problematic areas is the Save_Click section of the code where I wrote "This is a test" Thanks.
public partial class ListingSearch : Form
{
string line;
DialogResult result;
string fileName;
int i = 0;
string[] first = new string[100];
string[] last = new string [100];
string[] phone = new string [100];
string[] grade = new string [100];
public ListingSearch()
{
InitializeComponent();
MessageBox.Show("Please be sure to open a file before beginning");
}
private void OpenFile_Click(object sender, EventArgs e)
{
using (OpenFileDialog filechooser = new OpenFileDialog())
{
result = filechooser.ShowDialog();
fileName = filechooser.FileName;
System.IO.StreamReader file =
new System.IO.StreamReader(fileName);
while ((line = file.ReadLine()) != null)
{
string[] words = File.ReadAllText(fileName).Split(new string[] { "\n", "\r\n", ":" }, StringSplitOptions.RemoveEmptyEntries);
//firstName.Text = words[4];
//lastName.Text = words[5];
//telephone.Text = words[6];
//GPA.Text = words[7];
}
Read.Enabled = true;
}
}
private void Save_Click(object sender, EventArgs e)
{
File.AppendAllText(fileName, "This is a test");
}
private void Read_Click(object sender, EventArgs e)
{
MessageBox.Show(fileName);
MessageBox.Show(File.ReadAllText(fileName));
}
private void info_Click(object sender, EventArgs e)
{
first[i] = firstName.Text;
firstName.Text = " ";
last[i] = lastName.Text;
lastName.Text = " ";
phone[i] = telephone.Text;
telephone.Text = " ";
grade[i] = GPA.Text;
GPA.Text = " ";
i++;
}
private void displayinfo_Click(object sender, EventArgs e)
{
if (i == 0)
MessageBox.Show("Nothing to display!");
else
for (int j = 0; j < i; j++)
{
MessageBox.Show(first[j] + " " + last[j] + "\r" + phone[j] + "\r" + grade[j]);
}
}
You get error here
File.ReadAllText(fileName)
because you open same file before it here
System.IO.StreamReader file = new System.IO.StreamReader(fileName);
You need to close the file after you are finished reading it. Also, not sure why you are opening the file at all, since you subsequently use File.ReadAllText which will handle opening and closing the file all on its own.
Seems like your OpenFile_click event should just look like this:
using (OpenFileDialog filechooser = new OpenFileDialog())
{
result = filechooser.ShowDialog();
fileName = filechooser.FileName;
string[] words = File.ReadAllText(fileName).Split(new string[] { "\n", "\r\n", ":" }, StringSplitOptions.RemoveEmptyEntries);
Read.Enabled = true;
}
You haven't closed your StreamReader. C# will lock the file until you do. Or you could use a StreamWriter after you closed your StreamReader