How to insert file directory - c#

I made a program with iTextSharp which allows the user to click on a button to choose a file and do the main function with the second button.
Now I want to make a button which will replace this function in the second button:
using (Stream dest = File.Create(#"L:\Users\user\Documents\PDFnummerieren\PDF.pdf"))
I want to make a third button which will get the chosen location by the user, not a given location which is not changeable.
The whole Code:
private void button1_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(theFile) || !File.Exists(theFile))
return;
byte[] bytes = File.ReadAllBytes(theFile);
iTextSharp.text.Font blackFont = FontFactory.GetFont("Arial", 12,
iTextSharp.text.Font.NORMAL, BaseColor.BLACK);
using (Stream source = File.OpenRead(theFile))
using (Stream dest = File.Create(theCFile))
{
PdfReader reader = new PdfReader(source);
using (PdfStamper stamper = new PdfStamper(reader, dest))
{
int pages = reader.NumberOfPages;
for (int i = 1; i <= pages; i++)
{
ColumnText.ShowTextAligned(stamper.GetOverContent(i), Element.ALIGN_RIGHT,
new Phrase(i.ToString(), blackFont), 568f, 15f, 0);
}
}
}
}
private void button3_Click(object sender, EventArgs e)
{
var FD = new System.Windows.Forms.OpenFileDialog();
if (FD.ShowDialog() == System.Windows.Forms.DialogResult.OK)
theFile = FD.FileName;
}
private void button12_Click(object sender, EventArgs e)
{
var FD = new System.Windows.Forms.FolderBrowserDialog();
if (FD.ShowDialog() == System.Windows.Forms.DialogResult.OK) ;
}

Use the FolderBrowserDialog class to select a folder location.
You can combine the output folder and filename using Path.Combine(selectedFolder, filename) and place that in the using statement.
Code for saving the selected output folder:
private void button12_Click(object sender, EventArgs e)
{
var FD = new System.Windows.Forms.FolderBrowserDialog();
if (FD.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string selectedPath = FD.SelectedPath;
theCFile = Path.Combine(selectedPath, theFile)
}
}

Related

Save a copy of the file to specific folder, from a LinkLabel Hyperlink

I have a program that creates a list of hyperlinks to the files i search for. I can click the resulting hyperlink and the PDF opens. I would like to also have it make a copy of the pdf on my C: also without dialog. The source of the files is from the network. FileSearchButton_Click will search a directory for files with the content that match my search string.
aLinkLabel_LinkClicked is where I feel the copy action should be done
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.DirectoryServices;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace FindFilesBasedOnText
{
public partial class FileSearcherBasedOnSpecificText : Form
{
SmartTextBox DirectoryTextBox = new SmartTextBox();
SmartTextBox SearchTextBox = new SmartTextBox();
SmartButton SearchButton = new SmartButton();
SmartButton FileSearchButton = new SmartButton();
public FileSearcherBasedOnSpecificText()
{
InitializeComponent();
DirectoryTextBox.Location = new Point(70, 12);
DirectoryTextBox.ForeColor = Color.Black;
DirectoryTextBox.ForeColor = Color.Black;
this.Controls.Add(DirectoryTextBox);
SearchTextBox.Location = new Point(70, 43);
//SearchTextBox.Size = new Size(478, 20);
this.Controls.Add(SearchTextBox);
SearchButton.Location = new Point(526, 12);
SearchButton.Size = new Size(160, 23);
SearchButton.Text = "Search Directory";
SearchButton.TabStop = false;
SearchButton.Click += SearchButton_Click;
this.Controls.Add(SearchButton);
FileSearchButton.Location = new Point(526, 43);
FileSearchButton.Size = new Size(160, 23);
FileSearchButton.Text = "Search file based-on text";
FileSearchButton.TabStop = false;
FileSearchButton.Click += FileSearchButton_Click;
this.Controls.Add(FileSearchButton);
listBox1.AllowDrop = true;
listBox1.DragDrop += listBox1_DragDrop;
listBox1.DragEnter += listBox1_DragEnter;
listBox1.Focus();
}
private void listBox1_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop)) e.Effect = DragDropEffects.Copy;
}
private void listBox1_DragDrop(object sender, DragEventArgs e)
{
string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
foreach (string file in files)
listBox1.Items.AddRange(File.ReadAllLines(file));
}
private void SearchButton_Click(object sender, EventArgs e)
{
FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog();
DialogResult dialogReasult = folderBrowserDialog.ShowDialog();
if(!string.IsNullOrWhiteSpace(folderBrowserDialog.SelectedPath))
{
DirectoryTextBox.Text = folderBrowserDialog.SelectedPath;
}
}
public void FileSearchButton_Click(object sender, EventArgs e)
{
FilesPanel.Controls.Clear();
int i = 0;
int y = 5;
string filesName = string.Empty;
string rootfolder = DirectoryTextBox.Text.Trim();
string[] files = Directory.GetFiles(rootfolder, "*.*", SearchOption.AllDirectories);
foreach (string file in files)
{
try
{
string contents = File.ReadAllText(file);
if(contents.Contains(SearchTextBox.Text.Trim()))
{
i += 1;
LinkLabel aLinkLabel = new LinkLabel();
aLinkLabel.Text = file;
aLinkLabel.Location = new Point(5, y);
aLinkLabel.AutoSize = true;
aLinkLabel.BorderStyle = BorderStyle.None;
aLinkLabel.LinkBehavior = LinkBehavior.NeverUnderline;
aLinkLabel.ActiveLinkColor = Color.White;
aLinkLabel.LinkColor = Color.White;
aLinkLabel.BackColor = Color.Transparent;
aLinkLabel.VisitedLinkColor = Color.Red;
aLinkLabel.Links.Add(0, file.ToString().Length, file);
aLinkLabel.LinkClicked += aLinkLabel_LinkClicked;
FilesPanel.Controls.Add(aLinkLabel);
y += aLinkLabel.Height + 5;
}
else
{ // This shows DONE after each Search
LinkLabel aLinkLabel = new LinkLabel();
aLinkLabel.Font = new Font("", 12);
aLinkLabel.ActiveLinkColor = Color.White;
aLinkLabel.LinkColor = Color.White;
aLinkLabel.BackColor = Color.Transparent;
aLinkLabel.Text = "DONE";
FilesPanel.Controls.Add(aLinkLabel);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
void aLinkLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
LinkLabel lnk = new LinkLabel();
lnk = (LinkLabel)sender;
lnk.Links[lnk.Links.IndexOf(e.Link)].Visited = true;
System.Diagnostics.Process.Start(e.Link.LinkData.ToString());
//Create a directory if not exist for the file to be copied into
if (!System.IO.Directory.Exists(#"C:\Temp\RoHS_Docs"))
{
System.IO.Directory.CreateDirectory(#"C:\Temp\RoHS_Docs");
}
//Perform the file copy action on click
string CopyDestinationPath = #"C:\Temp\RoHS_Docs\";
System.IO.File.Copy(WHAT????, CopyDestinationPath, true);
}
private void FileSearcherBasedOnSpecificText_Load(object sender, EventArgs e)
{
}
private void pictureBox1_Click(object sender, EventArgs e)
{
FilesPanel.Controls.Clear();
}
private void label3_Click(object sender, EventArgs e)
{
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
SearchTextBox.Text = listBox1.SelectedItem.ToString();
}
private void label4_Click(object sender, EventArgs e)
{
}
private void progressBar1_Click(object sender, EventArgs e)
{
}
}
}

Save file to a specific folder in Windows Form C#

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;
}
}

Folder Browser Dialog with Environment

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.

Visual C# Express. Data can be save but until I close Visual C#

This Is the code for Adding the new Item...
private KrystalCafeDatabaseEntities kce = new KrystalCafeDatabaseEntities();
private Byte[] byteBLOBData;
public AddItem()
{
InitializeComponent();
cmbCategory.DataSource = kce.tblItemTypes;
cmbCategory.DisplayMember = "Name";
cmbCategory.ValueMember = "ItemType";
}
private void btnUpload_Click(object sender, EventArgs e)
{
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
FileStream fsBLOBFile = new FileStream(openFileDialog1.FileName, FileMode.Open, FileAccess.Read);
byteBLOBData = new Byte[fsBLOBFile.Length];
fsBLOBFile.Read(byteBLOBData, 0, byteBLOBData.Length);
fsBLOBFile.Close();
MemoryStream stmBLOBData = new MemoryStream(byteBLOBData);
pbImage.Image = Image.FromStream(stmBLOBData);
}
}
private void btnSave_Click(object sender, EventArgs e)
{
tblItem Item = new tblItem();
Item.Name = txtName.Text;
Item.Price = decimal.Parse(txtPrice.Text);
Item.Image = byteBLOBData;
Item.ItemType = (int)cmbCategory.SelectedValue;
kce.AddTotblItems(Item);
kce.SaveChanges();
MessageBox.Show("Record Saved! :D");
}
}
}
The program runs normally but the data will only be stored for awhile, then If i either closed my program or edit my code the data I just added will be lost.
One likely error is that KrystalCafeDatabaseEntities opens a transaction and you need to commit that transaction after calling SaveChanges.

How to print a document using C# code?

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());
}

Categories