I have a problem where a file won't download, even though it shows as completed.
The file is not showing in the location where it's supposed to be be downloaded to.
This is my code:
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if(e.ColumnIndex == 2)
{
int rowIndex = e.RowIndex;
DataGridViewRow row = dataGridView1.Rows[rowIndex];
string value1 = row.Cells[2].Value.ToString();
wc.DownloadFileCompleted += new AsyncCompletedEventHandler(AtlasCompleted);
Uri fileUrl = new Uri(value1);
Beta = fileUrl;
//Console.WriteLine(FormPopup.Variables.Location1.Length);
if (FormPopup.Variables.Location1 != null && FormPopup.Variables.Location1.Length >= 5)
{
Console.WriteLine(FormPopup.Variables.Location1);
Console.WriteLine(fileUrl);
wc.DownloadFileAsync(fileUrl, FormPopup.Variables.Location1);
//MessageBox.Show(fileUrl.ToString() + " " + FormPopup.Variables.Location1);
}
else
{
MessageBox.Show("Error: No file location specified.");
FormPopup form = new FormPopup();
form.Show(this);
}
}
}
private void AtlasCompleted(object sender, AsyncCompletedEventArgs e)
{
MessageBox.Show(Beta.ToString() + " " + FormPopup.Variables.Location1);
}
The file should download, but it's not downloading or appearing in the location specified.
If anyone can help that would be great, its really confusing me.
Thanks for the replies :D
The WebClient code is fine and it should download the file without any issues. Just ensure that your file Uri is correct (paste the uri into browser and see its correct). Path to save file on local system should be valid (folders included in path must exists) and regular user must have permissions to write.
To test it further, first use the hard-coded values:
wc.DownloadFileAsync("File Uril","File path at local system");
Example:
wc.DownloadFileAsync(new Uri("http://example.com/myfile.txt"), #"d:\myfile.txt");
Double check your variables for Uri and location because there is no magic that would prevent downloading besides invalid parameters.
Additionally, add some error logging/Exception handling so it tells you what happened.
private void AtlasCompleted(object sender, AsyncCompletedEventArgs e)
{
if(e.Error !=null)
Console.WriteLine(e.Error.Message);
else
Console.WriteLine("Completed");
MessageBox.Show(Beta.ToString() + " " + FormPopup.Variables.Location1);
}
Related
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.
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.
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.
I have this code in my application that allows user to download the newest version of the application. When the application download is finished, it opens a prompt if user wants to open the file location to see the file.
However, the tool launches two Message boxes instead of only once. I'm not sure if I'm missing something.
private void BTN_GNV_MouseUp(object sender, MouseButtonEventArgs e)
{
string URLDir = "http://shard.combatkingz.com/downloads/";
string URLName = "DayZ Config Tweak tool v" + Properties.Settings.Default.AvailableVersion + ".exe";
string URLFull = "";
using (WebClient DLWC = new WebClient())
{
URLFull = URLDir + URLName;
GlobalVars.DLPath = System.Environment.CurrentDirectory + "\\" + URLName;
try
{
DLWC.DownloadFileAsync(new Uri(URLFull), GlobalVars.DLPath);
DLWC.DownloadProgressChanged += DLWC_DownloadProgressChanged;
}
catch
{
MessageBox.Show("There was an error downloading the file.", GlobalVars.APPNAME, MessageBoxButton.OK, MessageBoxImage.Error);
#if DEBUG
#else
AddDownloadToDB("Failed");
#endif
}
}
}
void DLWC_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
PB_GNV.Width = (BTN_GNV.Width / 100) * e.ProgressPercentage;
if (PB_GNV.Width == BTN_GNV.Width && e.TotalBytesToReceive == e.BytesReceived)
{
MessageBoxResult nav = MessageBox.Show("New version downloaded. Do you want to navigate to the folder?", GlobalVars.APPNAME, MessageBoxButton.YesNo, MessageBoxImage.Error);
if (nav == MessageBoxResult.Yes)
{
string argument = #"/select, " + #GlobalVars.DLPath;
System.Diagnostics.Process.Start("explorer.exe", argument);
#if DEBUG
#else
AddDownloadToDB("Success");
#endif
}
}
}
I suspect that the DownloadProgressChanged event is firing on receiving the last byte and on the file completed. Using the DownloadFileCompleted event should resolve the problem.
I am working on a .NET program that is intended to iterate through a selected directory and allow the renaming of image files after displaying the images. I feel through my code that around 98% of the program is done, but I used a while loop to wait for the pressing of a button so as to allow for the renaming of the image file. Yet, the while loop freezes the program every time the while loop is iterated.
How can I either system("pause"); like in C++ to have the while loop pause without freezing the program and creating an infinite loop or how can I have the while loop paused automatically until a button is pressed?
Here is a tidbit of the code for the loop:
paused = true;
bool X = false;
label2.Text = "please choose a file name and press next";
//while statement
while (X == false)
{
if (paused == false)
{
//Renames filename
string newFileName = filenameTextbox.Text;
//Adds filename to selected directory where user wishes to send file to
string outputFile = destinationDirectory + "\\" + intCounter + fileNameOfficial;
//Pause statement to move to next operand..
//Copies post iterated file to selected directory
File.Copy(inputFile, outputFile, true);
X = true;
}
}
The code in its entirety is below.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Collections;
namespace recursionBitches
{
public partial class fileSorter : Form
{
bool paused = true;
public fileSorter()
{
InitializeComponent();
}
private void browseFrom_Click(object sender, EventArgs e)
{
//Warning dialouge for selecting a large file.
MessageBox.Show("Warning, before selecting the origination file, it is important to note that choosing too large of a directory (for example, my documents or 'C://') more than likely will cause this program to freeze. ");
MessageBox.Show("You have been warned");
//Choose the originating dir path. This dir path is to be later sorted using recursion.
//Once the originating dir path is chosen, it is added to the label above the button.
if (fromBrowse.ShowDialog(
) == DialogResult.OK)
{
this.originationLabel.Text = fromBrowse.SelectedPath;
}
}
private void browseTo_Click(object sender, EventArgs e)
{
//Choose the send to dir path. This dir path is to later have the files that are sorted sent to it.
//Once the to dir path is chosen, it is added to the label above the button.
if (toBrowse.ShowDialog(
) == DialogResult.OK)
{
this.sendingLabel.Text = toBrowse.SelectedPath;
}
}
private void sortButton_Click(object sender, EventArgs e)
{
string fileExtension = "*" + fileExtensionTextbox.Text;
//Check from path to ensure they are set to a user defined path.
int intCounter = 1;
if (originationLabel.Text != "From")
{
//Check to path to ensure it is set to a user defined path.
if (sendingLabel.Text != "To")
{
//Recursion stuff...
string sourceDirectory = fromBrowse.SelectedPath;
string destinationDirectory = toBrowse.SelectedPath;
//Sends origination path to function ae this is a function call. its num = 8675309... I think its name is Jenny.
recursiveRecursion(sourceDirectory, destinationDirectory, fileExtension, intCounter);
}
else
{
//Message box that says it is required to
MessageBox.Show("You dun goofed");
}
}
else
{
//Yup, it's a message box.
//That was an unhelpful comment....
/Aalmost as unhelpful as this comment
// This is what happens when I program stoned.
MessageBox.Show("You dun goofed");
}
//Grabs the path of the originating directory.
//After the originating directory path is choosen, send the path to a recursion function
//which will search the folders and sort the files in the dir. path.
}
private void originationLabel_Click(object sender, EventArgs e)
{
MessageBox.Show("Silly user, I am a label. I dont even click");
}
private void sendingLabel_Click(object sender, EventArgs e)
{
MessageBox.Show("Silly user, I am a label. I dont even click");
}
//Recursion function which grabs the directory path, uses a foreach loop to iterate through the files.
//Whilst each file is iterated through, have the recursive function select the files by extension and copy
//the files to another directory chosen by the user.
private void recursiveRecursion(string sourceDirectory, string destinationDirectory, string fileExtension, int intCounter)
{
//Select files Path and stuff
string[] filenames = Directory.GetFiles(sourceDirectory, fileExtension);
//foreach (string directoryName in directoryNames)
string[] directoryNames = Directory.GetDirectories(sourceDirectory);
//dir is the file name, as in for each file name in directory do the thing in this recursion loop thingy.
foreach (string fileName in filenames)
{
try
{
if (File.Exists(fileName))
{
//Don't use recursion. It is a file
//copy files here and stuff.
intCounter++;
//For the destination file ae dir2 to work, I need to get the file name from the file path.
//Currently dir is the file path.
//Enter code here to get the file name from the file path.
//Displays on label name of the file.
this.filesortTextbox.Text = "the file being copied is " + fileName;
//Gets filename from path
string fileNameOfficial = Path.GetFileName(fileName);
//Enters text of filename into filename textbox
filenameTextbox.Text = fileNameOfficial;
//For copying purposes, adds filename to originating directory path.
string inputFile = sourceDirectory + "\\" + fileNameOfficial;
//Assigns image from the origination directory.
Image img = Image.FromFile(inputFile);
// Shows image in the image viewer...
iteratedPicturebox.Image = img;
iteratedPicturebox.Width = img.Width;
iteratedPicturebox.Height = img.Height;
//Allows the user to change file name, after changing filename allows
//user to go to next file to rename. This is awesome for files...
paused = true;
bool X = false;
label2.Text = "Please choose a file name and press next.";
//while statement
while (X == false)
{
if (paused == false)
{
//Renames filename
string newFileName = filenameTextbox.Text;
//Adds filename to selected directory where user wishes to send file to.
string outputFile = destinationDirectory + "\\" + intCounter + fileNameOfficial;
//Pause statement to move to next operand..
//Copies post iterated file to selected directory.
File.Copy(inputFile, outputFile, true);
X = true;
}
}
}
else
{
//This really has an unknown pourpose, admittably keeping here for good luck...
Console.WriteLine("{0} is not a valid file or directory.", fileName);
}
}
catch (Exception e)
{
//What process failed you ask? Good question mate.
Console.WriteLine("The process failed: {0}", e.ToString());
}
}
//Long story short for each directory contained in the list of directories.
//Do the stuff listed in the foreach statement.
foreach (string directoryName in directoryNames)
{
try
{
if (Directory.Exists(directoryName))
{
//If this is a directory, send the thing through itself.
// MessageBox.Show("now going through the "+ directoryName + " directory");
recursiveRecursion(directoryName, destinationDirectory, fileExtension, intCounter);
this.directoryIterated.Text = "The Current Directory The Files Are being copied from is " + directoryName;
}
}
catch (Exception e)
{
Console.WriteLine("The process failed: {0}", e.ToString());
}
}
}
private void fileExtensionTextbox_TextChanged(object sender, EventArgs e)
{
}
private void label1_Click(object sender, EventArgs e)
{
}
private void directoryIterated_Click(object sender, EventArgs e)
{
MessageBox.Show("I am a label. I don't even click");
this.directoryIterated.Text = "You pressed me.";
}
private void kill_Click(object sender, EventArgs e)
{
Close();
}
private void filesortTextbox_Click(object sender, EventArgs e)
{
MessageBox.Show("I am a label. I don't even click.");
this.directoryIterated.Text = "You pressed me.";
}
private void iteratedPicturebox_Click(object sender, EventArgs e)
{
MessageBox.Show("I am a picture box, I don't even click.");
}
private void nextButton_Click(object sender, EventArgs e)
{
if (paused == false)
{
paused = true;
}
else
{
paused = false;
}
}
}
}
Consider using a BackgroundWorker for your processing loop. This allows you to process this on the background thread and won't freeze your main UI thread (which is what is happening)
Rather than trying to stop execution, I would display a dialog box:
Create form eg: FileRenameDialog.
Add public properties to form you can use to set From: text, etc.
Create instance of form. eg: FileRenameDialog reuseme
Whenever the user needs to make a selection, populate the text in the dialog. eg: reuseme.Source = "The current file being copied...";
Display the dialog to the user as modal eg: var dlgResult = reuseme.ShowDialog(this);
Do what you need to with the result eg: if (dlgResult == DialogResult.OK) {...do stuff with the properties of reuseme...}