how to Save File using C# Windows Application - c#

I'm using C# windows application .
I want to save files in my local system.
I used Open File dialog to attach the files.
Here the text inside the file is copying,I want the file itself to get copied with a new name.But what I am really looking for is , it should just save the file automatically and not show the SaveDialog Box?
How it can be done in windows application.Can anybody help me please?
The code is shown below:
private string GetFileName()
{
OpenFileDialog op1 = new OpenFileDialog();
DialogResult result = op1.ShowDialog();
if (result == DialogResult.OK) // Test result.
{
txtEn.Text = op1.FileName;
FileName = op1.FileName;
//MessageBox.Show(FileName);
File.Copy(op1.FileName, #"D:\Backup\");
}
return FileName;
}

SQL Server 2012 seems unrelated to your question. Provided that you have proper access rights to the target directory, then in order to automate the procedure (as per your question) you don't need to use the OpenFileDialog; just a single line should suffice the goal:
//Overwriting a file of the same name is not allowed
File.Copy(FileName, #"D:\Backup\" + FileName)
or
//Overwriting a file of the same name is allowed
File.Copy(FileName, #"D:\Backup\" + FileName, true)
You can also apply some additional logic pertinent to backup file naming (upon necessity).
Hope this may help. Best regards,

Are you trying to copy a file from some x location on your file system to y location (in your case D:\Backup folder) in the file system? If that is the requirement here, I see that you are using the FileName property of OpenFileDialog which gets the File path. This you are appending to D:\Backup. You should instead use the Path.GetFileName property to first extract the file name with extension and then append it to the new folder path
File.Copy(fileName, #"D:\Backup\" + Path.GetFileName(fileName));

Related

How to Get current date and create directory Everyday in C#?

get current date and make directory and second when directory is created, in that directory I have to store excel file and also save file as current date.
String Todaysdate = DateTime.Now.ToString("dd-MM-yyyy");
if (!Directory.Exists("C:\\Users\\Krupal\\Desktop\\" + Todaysdate))
{
Directory.CreateDirectory("C:\\Users\\Krupal\\Desktop\\" + Todaysdate);
}
This code have made directory with current date.
But when I want to store file in that directory, it generates the error:
Could not find a part of the path
'D:\WORK\RNSB\RNSB\bin\Debug\22-01-2020\22-01-2020.XLS
Belove path is store excel file that i have to store.
using (System.IO.StreamWriter file = new System.IO.StreamWriter(Todaysdate+"\\"+DateTime.Now.ToString("dd/MM/yyyy") +".XLS"))
Actually you are making the directory in a path then you are saving the .xls in another path.
You are making the directory using this path:
"C:\\Users\\Krupal\\Desktop\\" + Todaysdate
Then, here the path where you are trying to save the .xls:
Todaysdate+"\\"+DateTime.Now.ToString("dd/MM/yyyy") +".XLS"
The error shows the problem clearly, it could not fin this path:
D:\WORK\RNSB\RNSB\bin\Debug\22-01-2020\22-01-2020.XLS
While creating the .xls you are omitting the root path, so the process looks for the path 22-01-2020\22-01-2020.XLS in his working directory D:\WORK\RNSB\RNSB\bin\Debug.
You just need to align those paths: I sugget you to use relative paths, so here how you should fix your code:
String Todaysdate = DateTime.Now.ToString("dd-MM-yyyy");
if (!Directory.Exists(Todaysdate))
{
Directory.CreateDirectory(Todaysdate);
}
//then
using (System.IO.StreamWriter file = new System.IO.StreamWriter(Todaysdate+"\\"+DateTime.Now.ToString("dd/MM/yyyy") +".XLS"))
I presume you are running your WinForms application in Debug mode. This means that your current path is [your application path]\bin\Debug. If you look in file explorer, you will find that an executable has been created there. When using StreamWriter without an absolute file name, the file it tries to create is relative to the current execution path (in your case 'D:\WORK\RNSB\RNSB\bin\Debug'). StreamWriter will create a new file, if one does not exist, but it will not create a new folder, and you are passing it Todaysdate + "\\" which is effectively a new folder. Hence you are getting the error message.
To fix your problem, you need to provide the absolute path to your newly created directory thus:
using (System.IO.StreamWriter file = new System.IO.StreamWriter("C:\\Users\\Krupal\\Desktop\\" + Todaysdate+"\\"+DateTime.Now.ToString("dd/MM/yyyy") +".XLS"))
Winforms always expect directories inside Debug Folder, since it's EXE file is inside Debug and try to find it inside Debug folder.
In error it clearly shows that it is looking inside "Debug" folder.
Can you check whether File Exists in the mentioned folder created by you in C Drive.
// To Write File
System.IO.File.WriteAllLines(#"C:\Users\Public\TestFolder\WriteLines.txt", lines);
You can follow this MSDN Post, hope it helps, if Yes, please Upvote it
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/file-system/how-to-write-to-a-text-file

C#: opening a text file stored within the same project as the app

I managed to open a text file using an absolute path (in Visual Studio 2017) although if I change the location of my Solution folder the whole code would not work anymore as the actual physical path has changed and the code can not reference an existing location anymore.
I tried to create a text file within the same project and I would now like to open this file in my code, so if the location of the whole Solution changes the program can still work, would anyone be so kind to help me fix this issue?
I have also looked online for some different solution using code that references the current directory but I can't get my head around it as the current directory seems to be bin/debug and if I try to insert the file there the code doesn't recognize the location (also it doesn't look like a clean solution to me).
This is the code I am using so far in a WPF app, the whole purpose is to open the content of the text file containing countries listed line by line and to add them to a list box which will be displayed when a checkbox will be ticked.
private void listCountry_Initialized(object sender, EventArgs e)
{
listCountry.Visibility = Visibility.Hidden;
string path = "C:\\Users\\david\\source\\repos\\StudentRecord\\StudentRecordSystemMod\\StudentRecord\\country.txt";
if (File.Exists(path))
{
string[] myCountryFile = File.ReadAllLines(path);
foreach (var v in myCountryFile)
{
listCountry.Items.Add(v);
}
}
}
This is a great use case for OpenFileDialog Class.
Represents a common dialog box that allows a user to specify a filename for one or more files to open.
Here is the example of use, from the documentation.
// Configure open file dialog box
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
dlg.FileName = "Document"; // Default file name
dlg.DefaultExt = ".txt"; // Default file extension
dlg.Filter = "Text documents (.txt)|*.txt"; // Filter files by extension
// Show open file dialog box
Nullable<bool> result = dlg.ShowDialog();
// Process open file dialog box results
if (result == true)
{
// Open document
string filename = dlg.FileName;
}
Assuming C:\\Users\\david\\source\\repos\\StudentRecord\\StudentRecordSystemMod\\ is your project, and StudentRecord\\country.txt is a project folder and file in your project - you need change "Copy to Output Directory" to be "Always Copy" or "Copy If Newer" and "Build Action" to "Content" for the file in your project.
As you can see from the screenshot above, the folder structure for this content is created as well.
Then change your path assignment to be something like the following:
string path = string.Join(#"\", Application.ExecutablePath, #"StudentRecord\country.txt");
Clean and simple, place the file you want to open next to where the executable is generated, remember the executable path changes depending to if your project is in Debug or Release build mode. Now set:
string path = "country.txt";
By only providing a filename, the file is looked for in the same folder as the executable. Just remember that when you move the executable you must also move the file to the same place, but if you move the entire project folder then you're already set.
However, if you want to keep your file in a fixed location regardless of where you have your executable and/or VS project files, then the simplest path for it is:
string path = "C:\\country.txt";
This is an absolute path, but it's quite simple and very robust to changes, you would have to change the drive letter to break it and if C: is where your operating system files are then you probably won't do that.
If you don't like to have your files around in your root, you can always have a path like this:
string path = "C:\\ProjectNameFiles\\country.txt";
Or if you prefer to maintain a hierarchy of projects then you can use:
string path = "C:\\MyProjectsFiles\\ProjectName\\country.txt";
With this, every project can have a directory for the files it needs to open. These are all absolute paths, but are notably simpler than the one you posted, and they have a more fixed and organized structure.

Windows Forms app on shared location, save file locally

My problem is that I have a windows forms application which is located on a shared location, which is doing some logic and at the end i need to export the data into an excel file.
But the excel file should be exported to the machine that the users is logged in, not on the shared server where the application is hosted ...
Any Ideas?
Example of the situation:
The location of the application is at 192.168.1.150\AppName\App.exe
I have access to this shared location and I'm starting the exe file from there.
I need the application to export an excel file to my computer on my desktop .... how?
If you think the folder "My Documents" is a good place to save the Excel file, then this code will help to get you the path:
var folderPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
or if you want to put the file on the Desktop:
var folderPath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory)
The code works regardless of where the folder "My Documents" (or "Desktop") is located for the user (C:, D:, Network share, etc), or which language version his windows installation is using.
To combine with a time based file name:
var fileName = $"your_file_{DateTime.Now:yyMMddHHmmss}.xlsx";
var fullPath = Path.Combine(folderPath, fileName);
I often use time based file names to not overwrite if there is a previous file. (It would of course overwrite if created the same second)
If you want a file name that is guaranteed to be unique you can use a Guid instead of DateTime:
var fileName = $"your_file_{Guid.NewGuid():N}.xlsx";
If the file is just used "within the program" you can also store it in the temporary files folder. To get the path to the temporary files folder you write var folderPath = Path.GetTempPath()
Hope this helps!
Why don't you just use Save File Dialog and save the excel file where you want? Something like this:
private void SaveFile_FileOk(object sender, CancelEventArgs e)
{
string name = SaveFile.FileName;
string[] savearray = new string[] { "some test:" }
File.WriteAllLines(name, savearray);
//this is just an example, your excel file goes here.
}
And on your button to save:
SaveFile.ShowDialog();
You can choose the path for where you want to save...

asp file upload control, which one should be use?

ok, i found this on internet to upload some files.
if (FileUpload1.HasFile)
{
//create the path to save the file to
string fileName = Path.Combine(#"E:\Project\Folders", FileUpload1.FileName);
//save the file to our local path
FileUpload1.SaveAs(fileName);
}
and this
//check to make sure a file is selected
if (FileUpload1.HasFile)
{
//create the path to save the file to
string fileName = Path.Combine(Server.MapPath("~/Files"), FileUpload1.FileName);
//save the file to our local path
FileUpload1.SaveAs(fileName);
}
what is the difference, which one to use? i got confuse. by the way, if i can store file path in database, and next time when i want to delete or see that file, how can i retrieve that? so let say, first i add a record to database and uploaded a .doc file / excel file, next time when i want to edit that record, i want to retrieve the uploaded file, and show it in UI. thanks.
use second one cause it will convert relative or virtual path to real path itself . .u should get path from db and use it to resolve the path the same way you are storing and do manipulation on it delete and etc. for displaying url="~/Files/yourfilename"
yourfilefromdb -u retrieve it from db
string filepath = Path.Combine(Server.MapPath("~/Files"), yourfilefromdb);
File.Delete(filepath);
for showing
if it accessible directly u can just write url="~/Files/yourfilefromdb"
The only difference in two code blocks posted you is in specifying file path.
In case 1, static location is specified to save the file. It can cause problem, if location to save files differ in your production environment. It will require rebuild in that case.
While, in case 2, location is specified using relative path. So, it will always save files at "/Files" location.
//if you already know your folder is: E:\ABC\A then you do not need to use Server.MapPath, this last one is needed if you only have a relative virtual path like ~/ABC/A and you want to know the real path in the disk...
if (FileUpload1.HasFile)
{
string fileName = Path.Combine(#"E:\Project\Folders", FileUpload1.FileName);// they know the right path so .they using directly
FileUpload1.SaveAs(fileName);
}
if (FileUpload1.HasFile)
{
string fileName = Path.Combine(Server.MapPath("~/Files"), FileUpload1.FileName);// i don't know path is correct or not so they using Server.MapPath. . .
FileUpload1.SaveAs(fileName);
}

WPF copy file to the predefined directory

In a WPF app I need to make it possible for a user to pick a file by the standard Open File Dialog and save it to the predefined folder (user doesn't know where it is) right after the user click OK button on Open File Dialog. Something like of importing a file to the application. I do it in the following way:
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
dlg.Filter = "Text documents (.txt)|*.txt";
Nullable<bool> result = dlg.ShowDialog();
if (result == true)
{
string filename = dlg.SafeFileName;
System.IO.File.Copy(filename, #"E:\TestFolder\" + filename);
MessageBox.Show("File " + filename + " saved");
}
Is there a standard way to check if the file already exists before trying to save it and if it is really saved after saving it?
Look at System.File.Exists that should be able to tell you what you need to know.
The System.IO.File.Exists method returns true if a file at the given path exists, so you could use it to check both before and after your copy operation.
Use the SaveFileDialog (Microsoft.Win32). If you try to save over a file that already exists it will prompt you to make sure you want to save over that file. This doesn'y actually save it though, all it will do is provide the name and location of the file you want to create/save over. After you use the SaveFileDialog to select the file you then need to do the work of saving the file.
This post may be helpful

Categories

Resources