Download and save xml file on user local machine - c#

On my application I have a button used to save save an xlm file on specific uri indicated on my code. but I would like to give the user the possibility to save this file where he wants.
page.xaml
page.cs
private void Bt_Export_Click(object sender, RoutedEventArgs e)
{
CIRCUIT _selectedCircuit = (CIRCUIT)Lb_Circuits.SelectedItem;
busyIndicator.IsBusy = true;
this.DBContext.SaveXmlFile(_selectedCircuit.CIR_CIRCUIT, _action =>
{
if (!_action.HasError)
{
}
busyIndicator.IsBusy = false;
}, null);
}
//
public void SaveXmlFile(string XMlString)
{
XmlDocument XmlCircuit = new XmlDocument();
XmlCircuit.LoadXml(XMlString);
XmlCircuit.Save("C:/Users/izdoudou/Ciruit" + DateTime.Now.Date.ToString("yyMMddHHmm") + ".xml");
string ts= XmlCircuit.BaseURI;
}
Could you tell me if it is possible integrate this functionnality with silverlight, and how can I do it?
Kind regards,

You can use a FolderBrowserDialog for the purpose.
string foldername=#"C:\Users\izdoudou\Ciruit";
DialogResult result = folderBrowserDialog1.ShowDialog();
if( result == DialogResult.OK )
{
folderName = folderBrowserDialog1.SelectedPath;
}
In your code change
XmlCircuit.Save("C:/Users/izdoudou/Ciruit" + DateTime.Now.Date.ToString("yyMMddHHmm") + ".xml");
to
XmlCircuit.Save(foldername +"\\"+ DateTime.Now.Date.ToString("yyMMddHHmm") + ".xml");
Hope it helps.

Related

Using Tesseract in C#

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

Drag & Drop from internet browser (winforms)

Application I'm making give user ability to drag picture onto it and then copy this image to several folders at once.
Everything works great when I use local file, but I can't make it work with images dragged from internet browser directly on form.
Sure, image is saved in correct folders but name is changed to gibberish with .bmp extension.
So for example when I drag 100kb image with name "image.jpg" from browser I get 3mb image with name "sInFeER.bmp". I'm testing it on Firefox. I know I'm actually copying image from browser temp folder when I do that and file name is already changed there.
How can I keep correct file name and extension in this situation? (and preferably get image NOT converted to huge bmp file...)
Code I'm using for testing:
private void button10_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop, false) == true)
{
e.Effect = DragDropEffects.All;
}
}
private void button10_DragDrop(object sender, DragEventArgs e)
{
string[] draggedFiles = (string[])e.Data.GetData(DataFormats.FileDrop, false);
CatchFile(0, draggedFiles);
}
private void CatchFile(int id, string[] draggedFiles)
{
string directory = #”C:\test\”;
foreach (string file in draggedFiles)
{
Directory.CreateDirectory(directory);
File.Copy(file, directory + Path.GetFileName(file));
MessageBox.Show(Path.GetFileName(file)); // test
}
}
Thanks for all answers.
I've done some reading and decided that accessing original image when dragging from browser (Firefox) is pretty much impossible (without use of Firefox API), so I just used WebClient.DownloadFile to download dropped picture.
Here is code I ended with:
private void button10_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop, false) == true)
{
e.Effect = DragDropEffects.All;
}
}
private void button10_DragDrop(object sender, DragEventArgs e)
{
string draggedFileUrl = (string)e.Data.GetData(DataFormats.Html, false);
string[] draggedFiles = (string[])e.Data.GetData(DataFormats.FileDrop, false);
CatchFile(draggedFiles, draggedFileUrl);
}
private void CatchFile(string[] draggedFiles, string draggedFileUrl)
{
string directory = #"C:\test\";
foreach (string file in draggedFiles)
{
Directory.CreateDirectory(directory);
if (string.IsNullOrEmpty(draggedFileUrl))
{
if (!File.Exists(directory + Path.GetFileName(file))) File.Copy(file, directory + Path.GetFileName(file));
else
{
MessageBox.Show("File with that name already exists!");
}
}
else
{
string fileUrl = GetSourceImage(draggedFileUrl);
if (!File.Exists(directory + Path.GetFileName(fileUrl)))
{
using (var client = new WebClient())
{
client.DownloadFileAsync(new Uri(fileUrl), directory + Path.GetFileName(fileUrl));
}
}
else
{
MessageBox.Show("File with that name already exists!");
}
}
// Test check:
if (string.IsNullOrEmpty(draggedFileUrl)) MessageBox.Show("File dragged from hard drive.\n\nName:\n" + Path.GetFileName(file));
else MessageBox.Show("File dragged frow browser.\n\nName:\n" + Path.GetFileName(GetSourceImage(draggedFileUrl)));
}
}
private string GetSourceImage(string str)
{
string finalString = string.Empty;
string firstString = "src=\"";
string lastString = "\"";
int startPos = str.IndexOf(firstString) + firstString.Length;
string modifiedString = str.Substring(startPos, str.Length - startPos);
int endPos = modifiedString.IndexOf(lastString);
finalString = modifiedString.Substring(0, endPos);
return finalString;
}
There is probably better way of doing that but this works for me. Doesn't seem to work with other browsers. (but I needed it only to work with Firefox so I don't care)
Looks like you were dragging pixels from firefox to your app, not the url. I would look on the mozilla site for more info on how to drag the url to your app. They have lots of programming stuff and APIs to interact with the browser.

Issue with output location when saving file

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.

ZipFile extracting issue

screenshot
So this is a method that gets the directory of a file (is a .JDCEDFile but its is just renamed .zip file)
With this method i try to rename het file and extract it to a specified folder.
And show its contents into the right textboxes.
This method fails at Extracting process and i don't understand why.
public void OpenEncodedFile(string path)
{
// Variabelen + verwerking
string defaultpath = Application.StartupPath + #"\temp";
string defaultzip = path;
string defaultzipRename = defaultzip.Replace(".JDCEDFile", ".zip");
File.Move(defaultzip, defaultzipRename);
ZipFile.ExtractToDirectory(defaultzipRename, defaultpath);
Input.Text = File.ReadAllText(defaultpath + #"\tempData.txt");
Password.Text = File.ReadAllText(defaultpath + #"\tempPass.txt");
File.Move(defaultzipRename, defaultzip);
}
"path" has to be wrong, I just tested it and it worked fine.
private void openEncodedFileToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openEncodedFileDialog.ShowDialog() == DialogResult.OK)
{
OpenEncodedFile(openEncodedFileDialog.FileName);
}
}
This the the code.

C# WPF FileSaving Exception encountered

My issue is that I keep seeing a recurring theme with trying to allow my Notepad clone to save a file. Whenever I try to save a file, regardless of the location on the hard disk, the UnauthorizedAccess Exception continues to be thrown. Below is my sample code for what I've done, and I have tried researching this since last night to no avail. Any help would be greatly appreciated.
//located at base class level
private const string fileFilter = "Text Files|*.txt|All Files|*.*";
private string currentPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
private void MenuFileSaveAs_Click(object sender, RoutedEventArgs e)
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.DefaultExt = "*.txt";
sfd.Filter = fileFilter;
sfd.AddExtension = true;
sfd.InitialDirectory = currentPath;
sfd.RestoreDirectory = true;
sfd.OverwritePrompt = true;
sfd.ShowDialog();
try
{
System.IO.File.WriteAllText(currentPath,TxtBox.Text,Encoding.UTF8);
}
catch (ArgumentException)
{
// Do nothing
}
catch(UnauthorizedAccessException)
{
MessageBox.Show("Access Denied");
}
}
Change the following lines.
...
if (sfd.ShowDialog() != true)
return;
try
{
using (var stream = sfd.OpenFile())
using (var writer = new StreamWriter(stream, Encoding.UTF8))
{
writer.Write(TxtBox.Text);
}
}
...
I hope it helps you.
You need to get the correct path context and file object from the dialog box once the user has hit 'ok'. Namely verify the user actually hit ok and then use the OpenFile property to see what their file selection is:
if (sfd.ShowDialog.HasValue && sfd.ShowDialog)
{
if (sfd.OpenFile() != null)
{
// convert your text to byte and .write()
sfd.OpenFile.Close();
}
}

Categories

Resources