So I am trying to load text from a file location so I need to start off with creating a file location and then using that file location to load the text to my text boxes.
So I want to create the file location...
#"C:\Program Files (x86)\CPA\Text[number].txt"
Then in that location I would like to have my [number] text files
one.txt
two.txt
three.txt
four.txt
five.txt
six.txt
seven.txt
eight.txt
Then I need the tool to automatically load the text files to the text boxes
For my buttons to save the text I am using...
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "one|*.txt"; //Should I name it 'one.txt' instead ?
if (saveFileDialog.ShowDialog() != DialogResult.OK)
return;
File.WriteAllText(saveFileDialog.FileName, this.textBox1.Text);
I plan on using the following to get the location...
if (File.Exists(#"C:\Program Files (x86)\CPA\Text"))
{
//Load text to textboxes
}
But I am not sure how to load text to the text boxes automatically without asking the user to select the text files using open file dialogue
You can load the contents of a text file into a string variable using the File.ReadAllText method. You just pass this method the path to a file, and it will open the file, read the contents, return them as a string, and close the file.
You might consider keeping your files in a directory along with your executable. This way it's easy to find and always stays near your exe.
To get the directory that your executable lives in, you can do this:
// This requires "using System.Reflection" at the top of your .cs file
var thisExeDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
Then you might want to have a folder underneath that directory to store your files, like a "FileData" directory:
var myFileDirectory = Path.Combine(thisExeDirectory, "FileData");
If you don't want to do this, you can just do what you are already doing:
var myFileDirectory = #"C:\Program Files (x86)\CPA\Text[number].txt";
In any case, here's an example of how you can read the contents of a file into a textbox:
// Get the full path to the file
var filePath = Path.Combine(myFileDirectory, "one.txt");
// If it exists, write the contents to a textbox
if (File.Exists(filePath))
{
textBox1.Text = File.ReadAllText(filePath);
}
Now later, if you want to overwrite the file with the contents of the text box, you can use a similar method called File.WriteAllText:
// If the directory does not exist, create it
Directory.CreateDirectory(myFileDirectory);
File.WriteAllText(filePath, textBox1.Text);
Related
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.
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));
I am trying to replicate the standard save file process where, if there already exists a file with the necessary file extension, it is pre-selected in the SaveFileDialog. In my program I am using SaveFileDialog to allow the user to select the path for the file on the system. Upon save, it will automatically open to the path that the last saved file was, but the user has to re-select it.
Here is where I think something like this would come into play in my code:
Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
dlg.FileName = ".cct"; //The file extension
Nullable<bool> result = dlg.ShowDialog(); //Lets user select path
//**I'm guessing that the "pre-select" operation I am talking about
//would go here
directory = Path.GetDirectoryName(dlg.FileName); //Directory = File path on system
I have looked at the CheckFileExists property and it says that it "Gets or sets a value indicating whether a file dialog displays a warning if the user specifies a file name that does not exist." So it looks like it's more focused around checking whether or not the user enters a new file name.
How do I make it so that the previously saved file with the same extension is highlighted or selected in the SaveFileDialog if one is found upon save?
You can do a couple of things.
You could restore the path the user last saved with by setting dlg.RestoreDirectory = true.
Set the FileName before you show the dialog and it will automatically show that folder and insert the file name using dlg.FileName
http://msdn.microsoft.com/en-us/library/microsoft.win32.savefiledialog(v=vs.110).aspx
My program has a treeview which lists files from a remote computer. What I need to do is to copy these files from remote into one of my local folders. I wish that when I right click the file in treeview, a dialog box shows up for me to choose a folder, and then I click "OK" in the dialog box, my clicked file could be saved inside that folder.
Since the path of the files in remote is unc path, I'm using
File.Copy(string remote_address, string local_address)
to copy the files. As i said before I need a dialog window to choose folders. So I've tried using a FolderBowserDialog, however its SelectedPath property returns me only the path to the folder not including the folder's name! And I haven't found any property to return me the folder's name.
So my questions are:
If there's a way allowing me to use FolderBowserDialog, that I could get the full path of the location where I save my file?
If there's another method allowing me to copy or download the files from remote, like using SaveFileDialog. The problem is I don't know how to us it to do this.
The following should work:
var fbd = new FolderBrowserDialog();
if(fbd.ShowDialog() == DialogResult.OK)
{
var localPath= Path.Combine(fbd.SelectedPath, Path.GetFilename(remote_address));
File.Copy(remote_address, localPath);
}
I'm not sure which "SavePath" property you are referring to, as FolderBrowserDialog has no such property. The property you are looking for is called SelectedPath.
FolderBrowserDialog dlg = new FolderBrowserDialog();
dlg.ShowDialog();
string local_address = dlg.SelectedPath;
After you call the FolderBrowserDialog's ShowDialog() method it will return a variable indicating what button the user pressed (ie, Ok or Cancel)
after you make sure the user had used "Ok" to indicate they want to proceed with the operation, you can access the "SelectedPath" field which will give you the full local path they selected.
You can then get the final path by calling
System.IO.Path.Combine(fbd.SelectedPath,remoteFileName);
I'm assuming that fbd is your FolderBrowserDialog instance and remoteFileName should contain just the filename part of the remote file (eg. "MyFile.txt");
If you want to separate the filename from the full remote path, use
var remoteFileName = System.IO.Path.GetFileName(remotePath);
That being said, what a user would typically expect is not a folder browser dialog, but the save file dialog.
you can initialize the save file dialog with a filename, leaving the user to select a folder and possibly change the intended file name as well if they wish.
SaveFileDialog sfd = new SaveFileDialog();
sfd.FileName = remoteFileName;
sfd.ShowDialog();
sfd.FileName // now contains the full path to the file that the user has selected
don't forget to take the result from the ShowDialog() call to make sure the user didn't cancel out of the save dailog!
I have been trying to make sense of this http://msdn.microsoft.com/en-us/library/sfezx97z.aspx which uses the SaveFileDialog, but it is hard for me to understand. I have the following code:
FileInfo existingFile = new FileInfo("C:\\Users\\cle1394\\Desktop\\Apple Foreign Tax Payment Sample Layout Proposed - Sample Data.xlsx");
ConsoleApplication2.Program.ExcelData data = ConsoleApplication2.Program.GetExcelData(existingFile);
var json = new JavaScriptSerializer().Serialize(data);
How can I output the contents of json to a .json or .txt file?
I would like to let the user either see a link/ button to click to download/ save the file to a location on their computer, or, simply display the save file dialog box so that they can save the file to a location on their computer.
EDIT (to let OP comment on what parts are not clear):
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.ShowDialog();
if(saveFileDialog1.FileName != "")
{
File.WriteAllText(saveFileDialog1.FileName,json);
}
You are looking for this, then:
File.WriteAllText(#"c:\some\path\json.txt",json);
And note that it will save the file using UTF8-encoding without a Byte Order Mark. If you need the BOM, you need to use the File.WriteAllText(path, content, Enconding);
See here.
Update - adding sample with SaveFileDialog:
if(!string.IsNullOrEmpty(saveFileDialog.FileName))
{
//saveFileDialog.FileName should contain the full path
//according to the documentation: http://msdn.microsoft.com/en-us/library/system.windows.forms.filedialog.filename.aspx
File.WriteAllText(saveFileDialog.FileName,json);
}