Always asking file not present in bin/debug folder - c#

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

Related

How to open only a .dat file. In C#

I'm trying to open a file but I want it filter out to only .dat file.
using (OpenFileDialog fileChooser = new OpenFileDialog())
{
result = fileChooser.ShowDialog();
fileName = fileChooser.FileName; //Get file name.
fileChooser.Filter = "Data File|*.dat;";
fileChooser.DefaultExt = "dat";
fileChooser.AddExtension = true;
}
When having a OpenFileDialog in "using" the filter, defaultExt and Addextension doesn't work.
You should set filters before the call of "ShowDialog" method.
This should work.
using (var fileChooser = new OpenFileDialog())
{
// define the filters (first description | first filter; second description ...
fileChooser.Filter = "Data File|*.dat";
// select the first filter
fileChooser.FilterIndex = 1;
fileChooser.DefaultExt = "dat";
fileChooser.AddExtension = true;
// show the Opendialog
if (fileChooser.ShowDialog() == DialogResult.OK)
{
// get the path of specified file
var filename = fileChooser.FileName;
// use the filename to open the file...
}
}

Save file in current directory/path for an ID

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

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.

Extracting Path from OpenFileDialog path/filename

I'm writing a little utility that starts with selecting a file, and then I need to select a folder. I'd like to default the folder to where the selected file was.
OpenFileDialog.FileName returns the full path & filename - what I want is to obtain just the path portion (sans filename), so I can use that as the initial selected folder.
private System.Windows.Forms.OpenFileDialog ofd;
private System.Windows.Forms.FolderBrowserDialog fbd;
...
if (ofd.ShowDialog() == DialogResult.OK)
{
string sourceFile = ofd.FileName;
string sourceFolder = ???;
}
...
fbd.SelectedPath = sourceFolder; // set initial fbd.ShowDialog() folder
if (fbd.ShowDialog() == DialogResult.OK)
{
...
}
Are there any .NET methods to do this, or do I need to use regex, split, trim, etc??
Use the Path class from System.IO. It contains useful calls for manipulating file paths, including GetDirectoryName which does what you want, returning the directory portion of the file path.
Usage is simple.
string directoryPath = Path.GetDirectoryName(filePath);
how about this:
string fullPath = ofd.FileName;
string fileName = ofd.SafeFileName;
string path = fullPath.Replace(fileName, "");
if (openFileDialog1.ShowDialog(this) == DialogResult.OK)
{
strfilename = openFileDialog1.InitialDirectory + openFileDialog1.FileName;
}
You can use FolderBrowserDialog instead of FileDialog and get the path from the OK result.
FolderBrowserDialog browser = new FolderBrowserDialog();
string tempPath ="";
if (browser.ShowDialog() == DialogResult.OK)
{
tempPath = browser.SelectedPath; // prints path
}
Here's the simple way to do It !
string fullPath =openFileDialog1.FileName;
string directory;
directory = fullPath.Substring(0, fullPath.LastIndexOf('\\'));
This was all I needed for the full path to a file
#openFileDialog1.FileName

Categories

Resources