Save file in current directory/path for an ID - c#

Help! I'm searching hours for an solution. I'm doing the same as the examples in the internet, but there is always an error. (I'm new in coding..)
My main aim is to save a opened file which is selected in a new folder for a new ID.Have any ideas ?
var locationToCreateFolder = "C://";
var folderName = textBox1.Text + textBox6.Text;
var path = Path.Combine(locationToCreateFolder, folderName);
OpenFileDialog fbd = new OpenFileDialog();
fbd.Multiselect = true;
if (fbd.ShowDialog() == DialogResult.OK)
{
path = fbd.FileName;
}
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
File.Move(fbd.FileName, path);
//new FileInfo(locationToCreateFolder).Directory.Create();
}

Related

Save with different name in C# Form Application

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);

Always asking file not present in bin/debug folder

Is there any way i can take the data from the original location instead of copying the file to the bin/debug folder.
I am looking to send a file to my local printer. But my C# application is allowing to send file only when i copy the file to my bin/debug folder. Is there a way i can over come!!!
Codes:
private string image_print()
{
OpenFileDialog ofd = new OpenFileDialog();
{
InitialDirectory = #"C:\ZTOOLS\FONTS",
Filter = "GRF files (*.grf)|*.grf",
FilterIndex = 2,
RestoreDirectory = true
};
if (ofd.ShowDialog() == DialogResult.OK)
{
string filename_noext = Path.GetFileName(ofd.FileName);
string path = Path.GetFullPath(ofd.FileName);
img_path.Text = filename_noext;
string replacepath = #"bin\\Debug";
string fileName = Path.GetFileName(path);
string newpath = Path.Combine(replacepath, fileName);
if (!File.Exists(filename_noext))
{
// I don't like to copy the file to the debug folder
// is there an alternative solution?
File.Copy(path, newpath);
if (string.IsNullOrEmpty(img_path.Text))
{
return "";
}
StreamReader test2 = new StreamReader(img_path.Text);
string s = test2.ReadToEnd();
return s;
}
}
}
private void button4_Click(object sender, EventArgs e)
{
string s = image_print() + Print_image();
if (!String.IsNullOrEmpty(s) &&
!String.IsNullOrEmpty(img_path.Text))
{
PrintFactory.sendTextToLPT1(s);
}
}
Try this:
private string image_print()
{
string returnValue = string.Empty;
var ofd = new OpenFileDialog();
{
InitialDirectory = #"C:\ZTOOLS\FONTS",
Filter = "GRF files (*.grf)|*.grf",
FilterIndex = 2,
RestoreDirectory = true
};
if (ofd.ShowDialog() == DialogResult.OK &&
!string.IsNullOrWhiteSpace(ofd.FileName) &&
File.Exists(ofd.FileName))
{
img_path.Text = Path.GetFileName(ofd.FileName);
using (var test2 = new StreamReader(ofd.FileName))
{
returnValue = test2.ReadToEnd();
}
}
return returnValue;
}
It looks like the underlying issue is caused by these lines:
filename_noext = System.IO.Path.GetFileName(ofd.FileName); //this actually does include the extension!! It does not include the fully qualified path
...
img_path.Text = filename_noext;
...
StreamReader test2 = new StreamReader(img_path.Text);
You are getting the full file path from the OpenFileDialog then setting img_path.Text to just the file name. You are then using that filename (no path) to open the file for reading.
When you open a new StreamReader with just a filename it will look in the current directory for the file (relative to the location of the EXE, in this case bin/debug). Copying to "bin/debug" will probably not work in any other environment outside of your machine as the EXE will probably be deployed somewhere else.
You should use the full path to the selected file:
if (ofd.ShowDialog() == DialogResult.OK)
{
path = Path.GetFullPath(ofd.FileName);
img_path.Text = path;
if (string.IsNullOrEmpty(img_path.Text))
return "";//
StreamReader test2 = new StreamReader(img_path.Text);
string s = test2.ReadToEnd();
return s;
}

How to give custom made locations for downloading the file

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);
}
}
}
}
}

How to upload a filepath to local database and receive the file path when I click download button

The problem is when I am downloading the file, I can see the path in the download file. I am not getting the actual contents of the file inside.
When I am attaching a file called sample.txt and the path for sample.txt is== C:\Users\smohan\Downloads\databse\LocalDataBaseAp\sample.txt. I can see the path gets binded with my datagrid. But when I click the cell of the grid and download the same file. The file is downloading. But when I open.. The downloaded file I can see inside is missing the actual contents, but instead the path is saved as content (i.e.) C:\Users\smohan\Downloads\database\LocalDataBaseAp\sample.txt
What's wrong with my code?
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() == DialogResult.OK)
{
cncInfoDataGridView.Rows[dgvCell.RowIndex].Cells[1].Value = fileDialog.FileName;
SqlCeConnection cnn = new SqlCeConnection(Properties.Settings.Default.CncConnectionString);
//FileInfo fileInfo = new FileInfo(fileDialog.FileName);
byte[] imgData;
imgData = File.ReadAllBytes(fileDialog.FileName);}
}
}
/// <summary>
/// Download Attachment from the provided DataGridViewCell
/// </summary>
/// <param name="dgvCell"></param>
private void DownloadAttachment(DataGridViewCell dgvCell)
{
string strId = cncInfoDataGridView.Rows[dgvCell.RowIndex].Cells[1].Value.ToString();
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 = System.Text.Encoding.ASCII.GetBytes(s);
string strFileToSave = saveFileDialog1.FileName;
File.WriteAllBytes(saveFileDialog1.FileName, objData);
}
}
}
}
}
}
I understand what you're doing now; So, here's the pertinent code part:
objData = System.Text.Encoding.ASCII.GetBytes(s);
The problem is I think you are misunderstanding what System.Text.Encoding.ASCII.GetBytes(string) does. It does not read a file's contents; it encodes the string you pass to it. So, you are writing your file path from your Grid - not the contents of the file. This is more like what you want:
objData = File.ReadAllBytes(s);
That reads all the bytes from the file at the path you pass to it, returning a byte[], as you were using.

Display a neat set of files in my application

I have a set of files written to a temporary directory which I want to display to the user. In this instance I wish them to be able to select a file and then have the option of saving it. Is there a decent control in C# for doing this?
I think you could use OpenFileDialog and FolderBrowserDialog for example:
using (OpenFileDialog dialog = new OpenFileDialog())
{
dialog.InitialDirectory = "c:\\";//your temp directory path
dialog.Title = "Select files to move/copy";
if (dialog.ShowDialog() == DialogResult.OK)
{
string[] files = dialog.FileNames;
using (FolderBrowserDialog save = new FolderBrowserDialog())
{
save.Description = "Select location to save files";
if (save.ShowDialog() == DialogResult.OK)
{
foreach (string file in files)
{
FileInfo finfo = new FileInfo(file);
File.Move(file, save.SelectedPath + finfo.Name);
}
}
}
}
}
Would a simple Open File Dialog be sufficent? You can restrict it to only show the files with your temporary extension. OpenFileDialog in C# gives some examples of use.

Categories

Resources