Download a file and choose its location via FolderbrowserDialog - c#

I try to download a file and to be able to choose its locationenter image description here
Here is the code I made
in "use of the directory", that's where I define a directory, but I want to be able to choose it via "FolderbrowserDialog"

Please refer to the example here: https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.folderbrowserdialog?view=netframework-4.7.2
Specifically:
if(result == DialogResult.OK)
{
openFileName = openFileDialog1.FileName;
try
{
// Output the requested file in richTextBox1.
Stream s = openFileDialog1.OpenFile();
richTextBox1.LoadFile(s, RichTextBoxStreamType.RichText);
s.Close();
fileOpened = true;
}
catch(Exception exp)
{
MessageBox.Show("An error occurred while attempting to load the file. The error is:"
+ System.Environment.NewLine + exp.ToString() + System.Environment.NewLine);
fileOpened = false;
}

Related

Unable to copy a file from one directory to application folder

I am writing a c# desktop app where I want users to select a file from open file dialog after which the program will copy the file to where the application is executing from: here is my code that is not working at the moment
var dlg = new Microsoft.Win32.OpenFileDialog {
Title = "Select File",
DefaultExt = ".json",
Filter = "Json File (.json)|*.json",
CheckFileExists = true
};
if (dlg.ShowDialog() == true)
{
try
{
var currentDirectory = System.Windows.Forms.Application.ExecutablePath;
var destFile = Path.Combine(currentDirectory + "/temp/", dlg.FileName);
File.Copy(dlg.FileName, destFile, true);
}
catch (Exception ex)
{
MessageBox.Show(string.Format("An error occured: " + ex.Message));
}
}
Now I am getting the error that
the file is being used by another program
. When I edit the code that is meant to initiate the copy by removing true:
File.Copy(dlg.FileName, destFile);
I get the error that the
file already exists
in the directory where it is being selected from.
It seems, that you have an incorrect path to write into.
System.Windows.Forms.Application.ExecutablePath
returns exe file itself, not directory. Try
var destFile = Path.Combine(
Path.GetDirectoryName(Application.ExecutablePath), // Exe directory
"temp", // + Temp subdirectory
Path.GetFileName(dlg.FileName)); // dlg.FileName (without directory)
If you aren't sure that temp exists, you have to create it:
Directory.CreateDirectory(Path.GetDirectoryName(destFile));
Use below Code for Copy file from one folder to another folder.
string[] filePaths = Directory.GetFiles("Your Path");
foreach (var filename in filePaths)
{
string file = filename.ToString();
//Do your job with "file"
string str = "Your Destination"+file.ToString(),Replace("Your Path");
if (!File.Exists(str))
{
File.Copy(file , str);
}
}

Export To Disk throws error 'The System cannot find the specified path'

I am using the following code to export a crystal report in pdf format.
if (textBox1.Text == "" | textBox2.Text == "")
{
}
else
{
string filename = "\\" + textBox1.Text + ".pdf";
CreateEmptyFile(filename);
string file = textBox2.Text + "\\" + textBox1.Text + ".pdf";
labelget();
try
{
int idx = dataGridView1.CurrentCell.RowIndex;
string parv = dataGridView1.Rows[idx].Cells[0].FormattedValue.ToString();
ReportDocument wordreport = new ReportDocument();
wordreport.Load(#"C:\\FOLDER\\TESTREPORT.rpt");
wordreport.SetDatabaseLogon("root", "xxxxxxx", localhost, database);
wordreport.Refresh();
wordreport.SetParameterValue("bill_no", parv);
wordreport.SetParameterValue("fromterminal", this.terminal);
wordreport.ExportToDisk(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat, file);
}
catch (Exception em)
{
MessageBox.Show("error is: " + em);
}
}
Error Occurs in line wordreport.ExportToDisk saying the system could not find the specified path. I checked the permissions for the path where I created the PDF file, It all looks good.
How do i rectify this error?
I Found the Reason and answer for my question. I missed to add DSN details in admin tools.

Create a (text) file using FolderBrowserDialog

I created a notepad, however i want to save the file using the FolderBrowserDialog. Now i can't save the file because of this error: An unhandled exception of type 'System.NotSupportedException' occurred in mscorlib.dll
Additional information: The specified path is not supported.
this is the code i enterd:
private void Create_button_Click(object sender, EventArgs e)
{
DialogResult dialogResult = MessageBox.Show("Are you sure to make the file", "Sure?", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (dialogResult == DialogResult.Yes)
{
FolderBrowserDialog openfiledalog1 = new FolderBrowserDialog();
if (openfiledalog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string[] files = Directory.GetFiles(openfiledalog1.SelectedPath);
StreamWriter File = new StreamWriter(files + "." + groupBox3);
File.Write(textBox4);
}
}
else if (dialogResult == DialogResult.No)
{
}
}
can somebody help me?
a few things here to cause problems:
string[] files = Directory.GetFiles(openfiledalog1.SelectedPath);
Here you read the existing files in that directory. I thought you wanted to create a file? IN that case you provide a destination path, e.g.
var dest=Path.Combine(openfileDialog1.SelectedPath,"myfile.txt");
The following especially will not work:
StreamWriter File = new StreamWriter(files + "." + groupBox3);
You are passing a string array here. You need to pass a string as argument, not an array. See above. Also you try to name it like (which?) existing file + an extension determined by some groupBox3?
Writing the file, assuming that textBox4 contains the contents to be written, needs to be specified via the .Text property:
File.Write(textBox4.Text);
Please be specific as to which control or variable contains the desired output filename, which the contents, and what groupBox3 is supposed to provide.
Edit:
RadioButton suffix = groupBox3.Controls.OfType<RadioButton>().FirstOrDefault(n => n.Checked);
if (suffix == null)
MessageBox.Show("Please select a valid extension first");
else
{
var extension = suffix.Text;
FolderBrowserDialog openfiledalog1 = new FolderBrowserDialog();
if (openfiledalog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
var dest = Path.Combine(openfiledalog1.SelectedPath, "NewFile." + extension);
using (StreamWriter File = new StreamWriter(dest, false))
{
File.Write(textBox4.Text);
}
}
}

WebClient.DownloadFileTaskAsync and File.Exists

I'm using the following code to download a file and verify if the download succeeded:
try
{
UpdateAvailable = false;
Downloading = true;
using (var webclient = new WebClient { CachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore) })
{
var file = Path.Combine(basePath, filename);
await webclient.DownloadFileTaskAsync(updaterexe_fileurl, Path.Combine(basePath, updaterexe_filename));
await webclient.DownloadFileTaskAsync(updatefileurl, file);
}
if (!File.Exists(filename))
{
Error = "Error downloading update. Please try again.";
Log.Error("Error downloading update. Please try again (file does not exist).");
}
else
{
DownloadReady = true;
}
}
catch (Exception ex)
{
Log.Error("Error downloading update: " + ex);
Error = ex.Message;
}
finally
{
Downloading = false;
}
This works in most cases. But I got multiple reports from end-users that sometimes they get the 'try again' error message.
How is this even possible? Clearly, WebClient didn't throw an exception, but it also failed to download the file (it did not exist on disk).
Is this a caching issue? Am I missing any other error handling?
If it's a disk caching issue, I thought about adding the following:
int count = 0;
while (count < 3 || !File.Exists(filename))
{
Thread.Sleep(1000);
count++;
}
But this feels very hacky.
Any ideas?
You download to file, which is Path.Combine(basePath, filename) but you never check to see whether file exists, you check to see whether filename exists.
If basePath and the current working directory differ, the file "won't exist".

Verify if file exists or not in C#

I am working on an application. That application should get the resume from the users, so that I need a code to verify whether a file exists or not.
I'm using ASP.NET / C#.
You can determine whether a specified file exists using the Exists method of the File class in the System.IO namespace:
bool System.IO.File.Exists(string path)
You can find the documentation here on MSDN.
Example:
using System;
using System.IO;
class Test
{
public static void Main()
{
string resumeFile = #"c:\ResumesArchive\923823.txt";
string newFile = #"c:\ResumesImport\newResume.txt";
if (File.Exists(resumeFile))
{
File.Copy(resumeFile, newFile);
}
else
{
Console.WriteLine("Resume file does not exist.");
}
}
}
To test whether a file exists in .NET, you can use
System.IO.File.Exists (String)
if (File.Exists(Server.MapPath("~/Images/associates/" + Html.DisplayFor(modelItem => item.AssociateImage))))
{
<img src="~/Images/associates/#Html.DisplayFor(modelItem => item.AssociateImage)">
}
else
{
<h5>No image available</h5>
}
I did something like this for checking to see if an image existed before displaying it.
Try this:
string fileName = "6d294041-34d1-4c66-a04c-261a6d9aee17.jpeg";
string deletePath= "/images/uploads/";
if (!string.IsNullOrEmpty(fileName ))
{
// Append the name of the file to previous image.
deletePath += fileName ;
if (File.Exists(HttpContext.Current.Server.MapPath(deletePath)))
{
// deletevprevious image
File.Delete(HttpContext.Current.Server.MapPath(deletePath));
}
}
Simple answer is that you can't - you won't be able to check a for a file on their machine from an ASP website, as to do so would be a dangerous risk for them.
You have to give them a file upload control - and there's not much you can do with that control. For security reasons javascript can't really touch it.
<asp:FileUpload ID="FileUpload1" runat="server" />
They then pick a file to upload, and you have to deal with any empty file that they might send up server side.
You could use:
System.IO.File.Exists(#"c:\temp\test.txt");
Can't comment yet, but I just wanted to disagree/clarify with erikkallen.
You should not just catch the exception in the situation you've described. If you KNEW that the file should be there and due to some exceptional case, it wasn't, then it would be acceptable to just attempt to access the file and catch any exception that occurs.
In this case, however, you are receiving input from a user and have little reason to believe that the file exists. Here you should always use File.Exists().
I know it is cliché, but you should only use Exceptions for an exceptional event, not as part as the normal flow of your application. It is expensive and makes code more difficult to read/follow.
These answers all assume the file you are checking is on the server side. Unfortunately, there is no cast iron way to ensure that a file exists on the client side (e.g. if you are uploading the resume). Sure, you can do it in Javascript but you are still not going to be 100% sure on the server side.
The best way to handle this, in my opinion, is to assume that the user will actually select an appropriate file for upload, and then do whatever work you need to do to ensure the uploaded file is what you expect (hint - assume the user is trying to poison your system in every possible way with his/her input)
You wrote asp.net - are you looking to upload a file?
if so you can use the html
<input type="file" ...
In addition to using File.Exists(), you might be better off just trying to use the file and catching any exception that is thrown. The file can fail to open because of other things than not existing.
This may help you.
try
{
con.Open();
if ((fileUpload1.PostedFile != null) && (fileUpload1.PostedFile.ContentLength > 0))
{
filename = System.IO.Path.GetFileName(fileUpload1.PostedFile.FileName);
ext = System.IO.Path.GetExtension(filename).ToLower();
string str=#"/Resumes/" + filename;
saveloc = (Server.MapPath(".") + str);
string[] exts = { ".doc", ".docx", ".pdf", ".rtf" };
for (int i = 0; i < exts.Length; i++)
{
if (ext == exts[i])
fileok = true;
}
if (fileok)
{
if (File.Exists(saveloc))
throw new Exception(Label1.Text="File exists!!!");
fileUpload1.PostedFile.SaveAs(saveloc);
cmd = new SqlCommand("insert into candidate values('" + candidatename + "','" + candidatemail + "','" + candidatemobile + "','" + filename + "','" + str + "')", con);
cmd.ExecuteNonQuery();
Label1.Text = "Upload Successful!!!";
Label1.ForeColor = System.Drawing.Color.Blue;
con.Close();
}
else
{
Label1.Text = "Upload not successful!!!";
Label1.ForeColor = System.Drawing.Color.Red;
}
}
}
catch (Exception ee) { Label1.Text = ee.Message; }
I have written this code in vb and its is working fine to check weather a file is exists or not for fileupload control. try it
FOR VB CODE ============
If FileUpload1.HasFile = True Then
Dim FileExtension As String = System.IO.Path.GetExtension(FileUpload1.FileName)
If FileExtension.ToLower <> ".jpg" Then
lblMessage.ForeColor = System.Drawing.Color.Red
lblMessage.Text = "Please select .jpg image file to upload"
Else
Dim FileSize As Integer = FileUpload1.PostedFile.ContentLength
If FileSize > 1048576 Then
lblMessage.ForeColor = System.Drawing.Color.Red
lblMessage.Text = "File size (1MB) exceeded"
Else
Dim FileName As String = System.IO.Path.GetFileName(FileUpload1.FileName)
Dim ServerFileName As String = Server.MapPath("~/Images/Folder1/" + FileName)
If System.IO.File.Exists(ServerFileName) = False Then
FileUpload1.SaveAs(Server.MapPath("~/Images/Folder1/") + FileUpload1.FileName)
lblMessage.ForeColor = System.Drawing.Color.Green
lblMessage.Text = "File : " + FileUpload1.FileName + " uploaded successfully"
Else
lblMessage.ForeColor = System.Drawing.Color.Red
lblMessage.Text = "File : " + FileName.ToString() + " already exsist"
End If
End If
End If
Else
lblMessage.ForeColor = System.Drawing.Color.Red
lblMessage.Text = "Please select a file to upload"
End If
FOR C# CODE ======================
if (FileUpload1.HasFile == true) {
string FileExtension = System.IO.Path.GetExtension(FileUpload1.FileName);
if (FileExtension.ToLower != ".jpg") {
lblMessage.ForeColor = System.Drawing.Color.Red;
lblMessage.Text = "Please select .jpg image file to upload";
} else {
int FileSize = FileUpload1.PostedFile.ContentLength;
if (FileSize > 1048576) {
lblMessage.ForeColor = System.Drawing.Color.Red;
lblMessage.Text = "File size (1MB) exceeded";
} else {
string FileName = System.IO.Path.GetFileName(FileUpload1.FileName);
string ServerFileName = Server.MapPath("~/Images/Folder1/" + FileName);
if (System.IO.File.Exists(ServerFileName) == false) {
FileUpload1.SaveAs(Server.MapPath("~/Images/Folder1/") + FileUpload1.FileName);
lblMessage.ForeColor = System.Drawing.Color.Green;
lblMessage.Text = "File : " + FileUpload1.FileName + " uploaded successfully";
} else {
lblMessage.ForeColor = System.Drawing.Color.Red;
lblMessage.Text = "File : " + FileName.ToString() + " already exsist";
}
}
}
} else {
lblMessage.ForeColor = System.Drawing.Color.Red;
lblMessage.Text = "Please select a file to upload";
}

Categories

Resources