I'm trying to save a text file log to a specific location from my Windows Form project. I set the InitialDirectory to Path.GetFullPath(filePath) where I pass in filePath which is set as a simple path of "C:\MyWork\EventLogs\"
The log saves on Exit of the program (when a user closes or hits an Exit button), but it still saves in the Project\bin\Debug folder of my project.
Any ideas would be great. Thanks!
try
{
DateTime today = DateTime.Now;
string todayDate = today.ToString("yyyy-MM-dd_HHmm");
string fileName = (todayDate + "_EventLog" + ".txt").Trim();
string filePath = #"C:\MyWork\EventLogs\";
DirectoryInfo di = Directory.CreateDirectory(filePath);
SaveFileDialog sn = new SaveFileDialog
{
FileName = fileName,
AddExtension = true,
CheckPathExists = true,
Filter = "Text (*.txt)|*.txt",
OverwritePrompt = true,
InitialDirectory = Path.GetFullPath(filePath)
};
sn.RestoreDirectory = true;
StreamWriter SaveFile = new StreamWriter(fileName);
foreach (var item in EventLog)
{
SaveFile.WriteLine(item);
}
SaveFile.Close();
}
catch (Exception x)
{
MessageBox.Show(x.ToString());
}
You don't show the save dialog or use its FileName property in your current code, instead you refer to the initial fileName when saving.
So what you need to do is something like this instead:
if (sn.ShowDialog() == DialogResult.OK)
{
using (StreamWriter SaveFile = new StreamWriter(sn.FileName))
{
foreach (var item in EventLog)
{
SaveFile.WriteLine(item);
}
}
}
This will display the save dialog and assuming that the user clicks on OK the FileName of the save dialog should be the full path of where the user wants to save to.
You must show the Save Dialog for it to return the value you are expecting.
Related
I have problem when I try to save my spx file with different name.
I tried lots of ways but it did not work.
How can I save my voice recorder with different name ?
if (dataGridView1.Columns[e.ColumnIndex].Name == "Export")
{
using (var fbd = new FolderBrowserDialog())
{
DialogResult result = fbd.ShowDialog();
if (result == DialogResult.OK && !string.IsNullOrWhiteSpace(fbd.SelectedPath))
{
string files = fbd.SelectedPath;
string source = dataGridView1.Rows[e.RowIndex].Cells[6].Value.ToString();
string FileName = Path.GetFileName(source);
string DirectoryName = Path.GetDirectoryName(source);
try
{
File.Copy(Path.Combine(DirectoryName, FileName), Path.Combine(files, FileName));
}
catch (Exception)
{
MessageBox.Show("You have same voice recorder in that file.");
}
}
}
}
You just have to specify a new filename in the File.Copy command.
File.Copy(Path.Combine(DirectoryName, FileName), Path.Combine(files, "NewFileName"));
You just need to change the name on the end, if you need the user to input this name, you just have to put an new variable on the method
File.Copy(Path.Combine(DirectoryName, FileName), Path.Combine(files, newFileName));
Here if you want to use SaveFileDialog.
SaveFileDialog saveDialog = new SaveFileDialog();
saveDialog.ShowDialog();
CopyFile("C://", "New Text Document.txt", files, saveDialog.FileName);
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);
}
}
I have two methods: saveFile and saveAsToFile. The first one is supposed to overwrite the contents of the current, existing file. While the second is supposed to save as a new file (if the current is non-existing or the user just wants to make a copy.)
When I use the saveAsToFile method it works every time. When I use the saveFile method it doesn't write anything. (I DO see the "Saved!" MessageBox, though.)
Here are my methods:
public void saveFile(string[] inData, string inDataTitle)
{
//This method saves the file
SaveFileDialog savefile;
string trueFileName;
if (isStrArrayNotEmpty(inData)) {
//Only attempt to save the file if there is anything written in the textArea
if (f.getDocumentSavedStatus()) {
if (f.getDocumentChangedStatus()) {
savefile = new SaveFileDialog();
if (inDataTitle.EndsWith("*")) {
//Remove the asterisk from the document name
savefile.FileName = inDataTitle.Substring(0, inDataTitle.Length - 1);
}
else {
savefile.FileName = inDataTitle;
}
StreamWriter sw = new StreamWriter(savefile.FileName, false);
foreach (string line in inData) {
sw.WriteLine(line);
}
sw.Flush();
if (sw.BaseStream != null)
sw.BaseStream.Flush();
sw.Close();
/*
using (StreamWriter sw = new StreamWriter(savefile.FileName, false))
foreach (string line in inData) {
sw.WriteLine(line);
}
*/
f.setDocumentName(string.Empty);
trueFileName = Path.GetFileName(savefile.FileName);
f.setDocumentName(trueFileName);
f.setDocumentSavedStatus(true);
f.setDocumentChangedStatus(false); //Changes saved, status updated
MessageBox.Show("Saved!");
}
}
else {
//If the document hasn't been saved before, send the values to the 'Save As' method
saveAsToFile(inData, inDataTitle);
}
}
}
public void saveAsToFile(string[] inData, string inDataTitle)
{
//This method checks if there is anything written in the texArea,
//if so it prompts the user to save the file to disk (Save As)
SaveFileDialog savefile;
string trueFileName;
if (isStrArrayNotEmpty(inData)) {
//Only attempt to save the file if there is anything written in the textArea
savefile = new SaveFileDialog();
if (inDataTitle.EndsWith("*")) {
//Remove the asterisk from the document name
savefile.FileName = inDataTitle.Substring(0, inDataTitle.Length - 1);
}
else {
savefile.FileName = inDataTitle;
}
savefile.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
if (savefile.ShowDialog() == DialogResult.OK) {
StreamWriter sw = new StreamWriter(savefile.FileName, false);
foreach (string line in inData) {
sw.WriteLine(line);
}
sw.Flush();
if (sw.BaseStream != null)
sw.BaseStream.Flush();
sw.Close();
/*
using (StreamWriter sw = new StreamWriter(savefile.FileName))
foreach (string line in inData) {
sw.WriteLine(line);
}
*/
f.setDocumentName(string.Empty);
trueFileName = Path.GetFileName(savefile.FileName);
f.setDocumentName(trueFileName);
f.setDocumentSavedStatus(true);
f.setDocumentChangedStatus(false); //Changes saved, status updated
}
}
}
As you can see by the comments in the code; I tried using using, and then I tried to "manually flush" the streamwriter, but nothing works.
Using saveAsToFile works every time. It overwrites the text file as expected, no problems. While saveFile doesn't write anything to the file. (Leaving it unchanged.)
I tried looking for errors in saveFile by using MessageBox.Show to print the values of savefile.Filename and line in the appropriate places - they all worked as expected, yet nothing is written to the actual text file.
isStrArrayNotEmpty returns true if the string array does not contain any white spaces.
getDocumentSavedStatus returns the value of a boolean which tells if the file has been saved before or not (existent / non-existent)
getDocumentChangedStatus returns the value of a boolean which tells if the file has been modified or not (asterisk by the end of the file name, indicating that work will be lost if the user shuts down the application.)
Does the inDataTitle parameter include the path of the filename you're trying to save? If not, it's likely saving to a file of the same name but in a different folder.
After your line:-
StreamWriter sw = new StreamWriter(savefile.FileName, false);
add the line:-
MessageBox.Show(((FileStream)(sw.BaseStream)).Name);
and it'll tell you where the file is being saved.
Try replacing
StreamWriter sw = new StreamWriter(savefile.FileName, false);
foreach (string line in inData) {
sw.WriteLine(line);
}
sw.Flush();
if (sw.BaseStream != null)
sw.BaseStream.Flush();
sw.Close();
with
File.WriteAllLines(saveFile.Filename, inData);
I just wanted to know how can i give a custom made default location for grabbing the files.
I have uploaded a file to the local database and i have binded the file to the gird also. When i press download its showing an error called "the file is not found in location"
If i copy the particular uploaded files to the specified location i can download it easily.
So i just need to know how can i give a default location so that i can upload and downlaod the file from the same exact location.
snapshot of error: https://imageshack.com/i/ewTrmAI2j
Edited the same below code with custom made folder path. But i dont know why the file is always being asked from bin/debug/ folder. WHy its happening like this. IS there any way i can make changes to this folder.. other than bin/debug/ folder
Codes:
private void DownloadAttachment(DataGridViewCell dgvCell)
{
string fileName = Convert.ToString(dgvCell.Value);
//Return if the cell is empty
if (fileName == string.Empty)
return;
FileInfo fileInfo = new FileInfo(fileName);
string fileExtension = fileInfo.Extension;
byte[] byteData = File.ReadAllBytes(fileInfo.FullName); - - - - <<<<< ERROR HERE
//show save as dialog
using (SaveFileDialog saveFileDialog1 = new SaveFileDialog())
{
//Set Save dialog properties
saveFileDialog1.Filter = "Files (*" + fileExtension + ")|*" + fileExtension;
saveFileDialog1.Title = "Save File as";
saveFileDialog1.CheckPathExists = true;
saveFileDialog1.FileName = fileName;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
string s = cncInfoDataGridView.Rows[dgvCell.RowIndex].Cells[1].Value.ToString();
File.WriteAllBytes(saveFileDialog1.FileName, byteData);
byteData = System.Text.Encoding.ASCII.GetBytes(s);
}
}
}
The FileInfo() constructor only works with a full file path. It sounds like you are trying to use the constructor with just a file name, at which point it fails when you try to read the file because its not a valid path. There are a couple possibilities for dealing with this:
Create your own MyFileInfo() class inheriting from FileInfo() and add a constructor that appends your specific path to the filename.
Simply append the path in-line in your code as:
var myPath = #"c:\folder\stuff\";
FileInfo fileInfo = new FileInfo(myPath + fileName);
Normally the path would be setup as a setting in your app.config so you could change it easily if needed.
I found the answer
codes for the binding file path to the gridview and download the file using the file path
private void UploadAttachment(DataGridViewCell dgvCell)
{
using (OpenFileDialog fileDialog = new OpenFileDialog())
{
//Set File dialog properties
fileDialog.CheckFileExists = true;
fileDialog.CheckPathExists = true;
fileDialog.Filter = "All Files|*.*";
fileDialog.Title = "Select a file";
fileDialog.Multiselect = true;
if (fileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string strfilename = fileDialog.FileName;
cncInfoDataGridView.Rows[dgvCell.RowIndex].Cells[1].Value = strfilename;
}
}
}
/// <summary>
/// Download Attachment from the provided DataGridViewCell
/// </summary>
/// <param name="dgvCell"></param>
private void DownloadAttachment(DataGridViewCell dgvCell)
{
string fileName = Convert.ToString(dgvCell.Value);
if (!string.IsNullOrEmpty(fileName))
{
byte[] objData;
FileInfo fileInfo = new FileInfo(fileName);
string fileExtension = fileInfo.Extension;
//show save as dialog
using (SaveFileDialog saveFileDialog1 = new SaveFileDialog())
{
//Set Save dialog properties
saveFileDialog1.Filter = "Files (*" + fileExtension + ")|*" + fileExtension;
saveFileDialog1.Title = "Save File as";
saveFileDialog1.CheckPathExists = true;
saveFileDialog1.FileName = fileName;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
string s = cncInfoDataGridView.Rows[dgvCell.RowIndex].Cells[1].Value.ToString();
objData = File.ReadAllBytes(s);
File.WriteAllBytes(saveFileDialog1.FileName, objData);
}
}
}
}
}
I have a WPF application in which i have this method:
public static string getFile(List<string> extensions)
{
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
string ext = "files (", filter = "";
foreach (string s in extensions)
{
ext += s + ",";
filter += "*." + s + ";";
}
ext += ")";
dlg.Filter =ext+"|"+ filter;
Nullable<bool> result = dlg.ShowDialog();
if (result == true)
{
return dlg.FileName;
}
else return null;
}
I need to add another simple method which returns a folder path in which i will save new file.
How can i do this?
What is the best way to do it?
SaveFileDialog is what you need. From MSDN link:
// Configure save file dialog box
Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
dlg.FileName = "Document"; // Default file name
dlg.DefaultExt = ".text"; // Default file extension
dlg.Filter = "Text documents (.txt)|*.txt"; // Filter files by extension
// Show save file dialog box
Nullable<bool> result = dlg.ShowDialog();
// Process save file dialog box results
if (result == true)
{
// Save document
string filename = dlg.FileName;
}
I'd suggest having a look at the free Ookii Dialogs for WPF. I've used it on commercial projects in the past and it's always worked really well. Native support for WPF obviously but also has a lot of options for customization and provides more consistency across different versions of Windows.