So, I have this code i am programming under a button. When pressed, the user is asked if they want to download the newest File. If yes, then download it and the download location is supposed to be: Documents\Fiddler2 (You Get this Folder created when Installing Fiddler Classic).
However, after several different attempts, the file is only downloaded to the Documents Folder and needs to download to the Documents\Fiddler2 Folder. What am I doing wrong?
private void button4_Click(object sender, EventArgs e)
{
string title = "Check For New Version.";
string question = "Would you like to Check for any Updates?";
string url = "www.google.com";
if (DialogResult.Yes ==
MessageBox.Show(this, question, title,MessageBoxButtons.YesNo,MessageBoxIcon.Question))
{
string path = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
string path2 = Path.Combine(path, #"Fiddler2");
MessageBox.Show(path2);
Directory.SetCurrentDirectory(path2);
using (var client = new WebClient())
{
client.DownloadFile("https://drive.google.com/file/d/13K2IEH-FNQ2HhqAlvaYO3sEZoeWOtPMN/view?usp=sharing", "test.png");
}
}
Related
I'm trying to encrypt a file in a Windows 8.1 Store application, using an AES library found here. However, when I try to encrypt the file, I get a System.NotSupportedException.
I have tried entering the file path directly as a string, this gave the same error. When I look at the file path string (called savePath), it reads C:\Users\MyName\TheLibrary\TestDocument.doc
Here's my code:
private async void EncryptFile_Click(object sender, RoutedEventArgs e)
{
if (String.IsNullOrEmpty(filePathTextBox.Text) || String.IsNullOrEmpty(SaveLocationTextBox.Text))
{
MessageDialog msgDialog = new MessageDialog("Please select a file AND a save location", "");
await msgDialog.ShowAsync();
}
else
{
string format = "C:\\Users\\MyName\\";
string fileName = fileNameTextBox.Text;
string savePath = Path.Combine(format, folderPathTextBox.Text, fileName);
//encryption
SharpAESCrypt.SharpAESCrypt.Encrypt("password", filePathTextBox.Text, savePath);
EncryptStatus.Text = "File Sucessfully Encrypted";
}
}
Thanks for any help.
In my application I want to give user the option to download a PDF file. In my code, the file gets opened by browser; however, I want the file to be downloaded. Here's my code:
Controller
string name = id; //id is the name of the file
string contentType = "application/pdf";
var files = objData.GetFiles(); //list of files
string filename = (from f in files
orderby f.DateEncrypted descending
where f.FileName == name
select f.FilePath).First(); //gets the location of the file
string FullName = (from f in files
where f.FileName == name
select f.FileName).First(); //gets the new id in new location to save the file with that name
//Parameters to File are
//1. The File Path on the File Server
//2. The content type MIME type
//3. The parameter for the file save by the browser
return File(filename, contentType, FullName);
Here's how I'm using it in dropdown menu.
View:
<li><a id="copyURL" href="#Url.Action("Download", "Home", new { id = item.FileName})">Download</a></li>
By clicking on "Download", the file gets opened browser.
Set your content type to "application/octet-stream" so the PDF plugin won't try to pick it up and display it. Then the browser will handle it as a file download.
Download Files from Web:
This example shows how to download files from any website to local disk. The simply way how to download file is to use WebClient class and its method DownloadFile. This method has two parameters, first is the url of the file you want to download and the second parameter is path to local disk to which you want to save the file.
Download File Synchronously
The following code shows how to download file synchronously. This method blocks the main thread until the file is downloaded or an error occur (in this case the WebException is thrown).
[C#]:
using System.Net;
WebClient webClient = new WebClient();
webClient.DownloadFile("pdf file address", #"c:\myfile.pdf");
Download File Asynchronously:
To download file without blocking the main thread use asynchronous method DownloadFileAÂsync. You can also set event handlers to show progress and to detect that the file is downloaded.
[C#]:
private void btnDownload_Click(object sender, EventArgs e)
{
WebClient webClient = new WebClient();
webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);
webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);
webClient.DownloadFileAsync(new Uri("pdf file address"), #"c:\myfile.pdf");
}
private void ProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
progressBar.Value = e.ProgressPercentage;
}
private void Completed(object sender, AsyncCompletedEventArgs e)
{
MessageBox.Show("Download completed!");
}
ref: http://www.csharp-examples.net/download-files/
Browser will try to show the file unless you specify not to.
Try Adding ContentDisposition before returning File.
var cd = new System.Net.Mime.ContentDisposition
{
FileName = filename,
Inline = false,
};
Response.AppendHeader("Content-Disposition", cd.ToString());
return File(filename, contentType, FullName);
I am working on a WinForm Application using c#. I am using a button to browse for an image file (.jpeg or .bmp). When the user browses the file and clicks ok, on the click of another "Proceed or Update" button, I want that the browsed file should be renamed and saved to a predefined directory where all image files will be saved by default, without much user interaction!
How can I achieve this? I have used openFileDialog for browsing the file, but dont know what else to do.
//detination filename
string newFileName = #"C:\NewImages\NewFileName.jpg";
// if the user presses OK instead of Cancel
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
//get the selected filename
string filename = openFileDialog1.FileName;
//copy the file to the new filename location and overwrite if it already exists
//(set last parameter to false if you don't want to overwrite)
System.IO.File.Copy(filename, newFileName, true);
}
More information on the Copy method.
First you have to implement a copy function that can make unique file names:
private void CopyWithUniqueName(string source,
string targetPath,
string targetFileName)
{
string fileName = Path.GetFileNameWithoutExtension(targetFileName);
string extension = Path.GetExtension(targetFileName);
string target = File.Exists(Path.Combine(targetPath, targetFileName);
for (int i=1; File.Exists(target); ++i)
{
target = Path.Combine(targetPath, String.Format("{0} ({1}){2}",
targetFileName, i, extension));
}
File.Copy(source, target);
}
Then you can use it, suppose defaultTargetPath is the default target file where to copy images and defaultFileName is the default file name for images:
void button1_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() != DialogResult.OK)
return;
CopyWithUniqueName(openFileDialog1.FileName,
defaultTargetPath, defaultFileName);
}
In case of multiple selection:
foreach (string fileName in openFileDialog1.FileNames)
{
CopyWithUniqueName(fileName,
defaultTargetPath, defaultFileName);
}
You'll get this (suppose defaultFileName is "Image.png"):
Source Target
A.png Image.png
B.png Image (1).png
C.png Image (2).png
You can do that with the File.Copy()-method. Just put the predefined directory and the new filename as the destination parameter.
For more info see here
I'm trying to build a copier so that you use the openFileDialog to chose a file and then the folderBrowserDialog to choose the location to copy it to.
The problem I'm having is that when I use File.Copy(copyFrom,copyTo) it gives me an exception that I can't copy to a directory.
Is there anyway around this, or am I just missing something stupid and noobish. I've tryed useing openFD for choosing both locations and have just tried using the folderBD to see if it made a difference.
I know there should be if statements there to catch the exceptions but this is a rough draft of the code to get working 1st.
Thanks in advance for the help, code attached.
// Declare for use in all methods
public string copyFrom;
public string copyTo;
public string rootFolder = #"C:\Documents and Settings\cmolloy\My Documents";
private void btnCopyFrom_Click(object sender, EventArgs e)
{
// uses a openFileDialog, openFD, to chose the file to copy
copyFrom = "";
openFD.InitialDirectory = rootFolder;
openFD.FileName = "";
openFD.ShowDialog();
// sets copyFrom = to the file chosen from the openFD
copyFrom = openFD.FileName;
// shows it in a textbox
txtCopyFrom.Text = copyFrom;
}
private void btnCopyTo_Click(object sender, EventArgs e)
{
//uses folderBrowserDialog, folderBD, to chose the folder to copy to
copyTo = "";
this.folderBD.RootFolder = System.Environment.SpecialFolder.MyDocuments;
this.folderBD.ShowNewFolderButton = false;
folderBD.ShowDialog();
DialogResult result = this.folderBD.ShowDialog();
// sets copyTo = to the folder chosen from folderBD
copyTo = this.folderBD.SelectedPath;
//shows it in a textbox.
txtCopyTo.Text = copyTo;
}
private void btnCopy_Click(object sender, EventArgs e)
{
// copys file
File.Copy(copyFrom, copyTo);
MessageBox.Show("File Copied");
You have to append the file name to the directory path. Do this:
string destinationPath = Path.Combine(copyTo, Path.GetFileName(copyFrom));
File.Copy(copyFrom, destinationPath);
(with this you'll copy selected file to another directory with the same name of the original one and it'll throw an exception if the same file already exist in that directory)
Edit
Side note: do not hard code the path in your source code, use this:
rootFolder = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
to get the path of current user's documents folder.
Do this:
File.Copy(copyFrom, Path.Combine(copyTo, Path.GetFileName(copyFrom)));
File.Copy needs to know the full path of the new file you want, including the file name. If you just want to use the same file name, you can use this to append the file name to the path:
copyTo = Path.Combine(copyTo, Path.GetFileName(copyFrom));
I have written two methods such as FileUpLoad() and FileDownLoad() to Upload and Download a single file in my local system.
void FileUpLoad()
{
string hfBrowsePath = fuplGridDocs.PostedFile.FileName; //fuplGridDocs is a fileupload control
if (hfBrowsePath != string.Empty)
{
string destfile = string.Empty;
string FilePath = Path.Combine(#"E:\Documents\");
FileInfo FP = new FileInfo(hfBrowsePath);
hfFileNameAutoGen.Value = PONumber + FP.Extension;
destfile = FilePath + hfFileNameAutoGen.Value; //hfFileNameAutoGen is a hidden field
fuplGridDocs.PostedFile.SaveAs(destfile);
}
}
void FileDownLoad(LinkButton lnkFileName)
{
string filename = lnkFileName.Text;
string FilePath = Path.Combine(#"E:\Documents", filename);
fuplGridDocs.SaveAs(FilePath);
FileInfo fileToDownLoad = new FileInfo(FilePath);
if (fileToDownLoad.Exists)
{
Process.Start(fileToDownLoad.FullName);
}
else
{
lblMessage.Text = "File Not Saved!";
return;
}
}
While running the application before hosting it in IIS, I can upload a file to the desired location and can also retrieve a file from the saved location. But after publishing it in the localhost, I can only Upload a file. I could not download the saved file. There is no exception too. The Uploaded file is saved in the desired location. I don't know why it is not retrieving the file? Why I cant download the file in IIS? I have searched a lot in the internet, but couldn't find the solution. How to solve this? I am using Windows XP and IIS 5.1 version.
How do you expect your Web Application to do a Process.Start when you deploy this site to a server, your just going to be opening pictures on the server, not on the client PC.
I think this will answer your question: http://www.codeproject.com/Articles/74654/File-Download-in-ASP-NET-and-Tracking-the-Status-o
Also the download file is missing a slash after E:\Documents
another option is to add your wildcard to IIS MIME types