Empty path name is not legal Error - c#

I'm trying to save a 2 images to my database but i keep on getting the above error, i have tried a lot but just cant solve it.
string fileName = "";
string fileName2 = "";
private void SaveReq()
{
try
{
byte[] img = null;
byte[] img2 = null;
FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
FileStream fs2 = new FileStream(fileName2, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
BinaryReader br2 = new BinaryReader(fs2);
img = br.ReadBytes((int)fs.Length);
img2 = br2.ReadBytes((int)fs2.Length);
SqlConnection CN = new SqlConnection(mysql.CON.ConnectionString);
string Query = "insert into BUILD_LIC (ID,KROKY,KROKY_3AM) values('" + txtID.Text + "',#KROKY,#KROKY_3AM)";
CN.Open();
mysql.COMMAND = new SqlCommand(Query, CN);
mysql.COMMAND.Parameters.Add(new SqlParameter("#KROKY", img));
mysql.COMMAND.Parameters.Add(new SqlParameter("#KROKY_3AM", img2));
mysql.COMMAND.ExecuteNonQuery();
CN.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
if i delete one of the filestreams(fs,fs2) the code work & save image put this only for one & i want to save the two images could u show me how to do that by correcting my code

Make sure that the filename value has a valid file path.
From FileStream Constructor (String, FileMode, FileAccess)
Throws ArgumentException if path is an empty string (""), contains
only white space, or contains one or more invalid characters.
You might want to have a look at File.Exists Method
Determines whether the specified file exists.

The error message is telling you exactly the issue, and it appears obvious in the code you posted:
string fileName = "";
string fileName2 = "";
You then call the FileStream constructors with the above variables, but I don't see where you've set them to anything other than "":
FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
FileStream fs2 = new FileStream(fileName2, FileMode.Open, FileAccess.Read);
You'll need to give valid path/filenames to those two variables to resolve this error. For example:
string fileName = #"C:\Temp\File1.txt";
string fileNAme = #"C:\Temp\File2.txt";

Related

C# - Trying to grab and save a pdf into my database

In my C# application, I am trying to make it able to pull a pdf and save it, so that end users can press a button and pull up that pdf while they are in the application. But when I copy the content to the filestream it makes the pdf but it is just blank with nothing from the original pdf. What am I doing wrong?
The pdf's could also have pictures on them, and I don't think the way I'm doing it would allow those to be brought over.
Microsoft.Win32.OpenFileDialog openFileDialog = new Microsoft.Win32.OpenFileDialog();
bool? response = openFileDialog.ShowDialog();
var fileContent = string.Empty;
var filestream = openFileDialog.OpenFile();
using (StreamReader reader = new StreamReader(filestream))
{
fileContent = reader.ReadToEnd();
}
// make folder path
string FolderPath = "ProjectPDFs\\";
string RootPath = "X:\\Vents-US Inventory";
DirectoryInfo FolderDir = new DirectoryInfo(Path.Combine(RootPath, FolderPath));
Directory.CreateDirectory(FolderDir.ToString());
string filePath = "";
string FileName = openFileDialog.SafeFileName;
if (fileContent.Length > 0)
{
filePath = Path.Combine(FolderDir.ToString(), FileName);
using (Stream fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write))
{
byte[] bytestream = Encoding.UTF8.GetBytes(fileContent);
Stream stream = new MemoryStream(bytestream);
stream.CopyTo(fileStream);
}
}

C# Empty path name is not legal - Winform

Below this code is my Add button on my windows form. When i tried to click it without adding any image & without path also, error occur that i mentioned below these code. I want to fix this exception, even if the user doesn't add image or file path it doesn't get exception. I know its been asked many times but their exception in their code is different so i'm a bit confused there. Thank you
private void btn_add_Click(object sender, EventArgs e)
{
byte[] image = null;
var stream = new FileStream(this.txt_path.Text, FileMode.Open, FileAccess.Read);
var read = new BinaryReader(stream);
image = read.ReadBytes((int)stream.Length);
using (var con = SQLConnection.GetConnection())
{
if (string.IsNullOrEmpty(cbox_supplier.Text) || string.IsNullOrEmpty(txt_code.Text) || string.IsNullOrEmpty(txt_item.Text) || string.IsNullOrEmpty(txt_quantity.Text) || string.IsNullOrEmpty(txt_cost.Text) || string.IsNullOrEmpty(txt_path.Text))
{
MetroMessageBox.Show(this, "Please input the Required Fields", "System Message:", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
else
{
var selectCommand = new SqlCommand("Insert into employee_product (Image, Supplier, Codeitem, Itemdescription, Date, Quantity, Unitcost) Values (#Image, #Supplier, #Codeitem, #Itemdescription, #Date, #Quantity, #Unitcost)",con);
selectCommand.Parameters.AddWithValue("#Image", image);
selectCommand.Parameters.AddWithValue("#Supplier", cbox_supplier.Text);
selectCommand.Parameters.AddWithValue("#Codeitem", txt_code.Text.Trim());
selectCommand.Parameters.AddWithValue("#Itemdescription", txt_item.Text.Trim());
selectCommand.Parameters.AddWithValue("#Date", txt_date.Text.Trim());
selectCommand.Parameters.AddWithValue("#Quantity", txt_quantity.Text.Trim());
selectCommand.Parameters.AddWithValue("#Unitcost", txt_cost.Text.Trim());
selectCommand.ExecuteNonQuery();
MessageBox.Show("Added successfully", "SIMS", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
txt_path.Clear();
pictureBox1.Image = null;
txt_code.Clear();
txt_item.Clear();
txt_quantity.Clear();
txt_cost.Clear();
_view.AddingProduct();
}
}
}
private void btn_upload_Click(object sender, EventArgs e)
{
OpenFileDialog opnfd = new OpenFileDialog();
opnfd.Filter = "Image Files (*.jpg;*.jpeg;.*.gif;*.png;)|*.jpg;*.jpeg;.*.png;*.gif";
opnfd.Title = "Select Item";
if (opnfd.ShowDialog() == DialogResult.OK)
{
var path = opnfd.FileName.ToString();
txt_path.Text = path;
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
pictureBox1.Image = Image.FromFile(opnfd.FileName);
}
}
// This is where System Argument Exception occur
byte[] image = null;
-----> var stream = new FileStream(this.txt_path.Text, FileMode.Open, FileAccess.Read);
var read = new BinaryReader(stream);
image = read.ReadBytes((int)stream.Length);
You can either pre-check the file exists:
if (File.Exists(txt_path.Text))
{
var stream = new FileStream(this.txt_path.Text, FileMode.Open, FileAccess.Read);
var read = new BinaryReader(stream);
image = read.ReadBytes((int)stream.Length);
// The rest of your code
}
or catch the error when it occurs:
try
{
var stream = new FileStream(this.txt_path.Text, FileMode.Open, FileAccess.Read);
var read = new BinaryReader(stream);
image = read.ReadBytes((int)stream.Length);
// The rest of your code
}
catch
{
// Creating filestream object failed.
}
As you asked about wrapping the FileStream in a using statement:
When you open a FileStream you need to explicitly close it and make sure you've disposed of it to remove the open file handle - so that other applications can access the file. You can either do this by calling Close and Dispose or you can just wrap the object in a using statement that will automatically call close and dispose for you.
using (var stream = new FileStream(this.txt_path.Text, FileMode.Open, FileAccess.Read))
{
using (var read = new BinaryReader(stream))
{
image = read.ReadByres((int)stream.Length);
} // BinaryReader is Closed and Disposed here
} // FileStream is Closed and Disposed here
The FileStream and BinaryReader objects (stream and read) only exist up to the point where the using statements closing brace } is.

Some times don't want to add image still showing "empty Path name is not legal in c#"

I am making an Winform Application with SQLite.
I am working with Load Image function into my C# winform Application. At some point user need to add Image and some time user don't need to add images.When form of image load left blank and before saving the form it is showing exception "empty Path name is not legal". Exception occurs on below code
byte[] imageBt = null;
FileStream fstream = new FileStream(this.cnicloc_txt.Text, FileMode.Open,
FileAccess.Read);
BinaryReader br = new BinaryReader(fstream);
imageBt = br.ReadBytes((int)fstream.Length);
And my Load Image code is as follows
private void loadImage_btn_Click(object sender, EventArgs e)
{
OpenFileDialog dlg = new OpenFileDialog();
dlg.Filter = "JPG Files(*.jpg)|*.jpg|PNG Files(*.png)|*.png|All Files(*.*)|*.*";
dlg.Title = "Select CNIC of Owner...";
if(dlg.ShowDialog()==DialogResult.OK)
{
string picPath = dlg.FileName.ToString();
cnicloc_txt.Text = picPath;
}}
I am new here please forgive me if I commit any nonsense
It is a good idea to test the values before you pass them to constructors. Test the value of this.cnicloc_txt.Text, if null abort the operation. Do something like this:
string file = this.cnicloc_txt.Text;
if (!string.IsNullOrWhiteSpace(file))
{
byte[] imageBt = null;
FileStream fstream = new FileStream(file, FileMode.Open,
FileAccess.Read);
BinaryReader br = new BinaryReader(fstream);
imageBt = br.ReadBytes((int)fstream.Length);
}
Happy coding :)
if (!string.IsNullOrWhiteSpace(cnicloc_txt.Text))
{
if (!File.Exists(cnicloc_txt.Text))
{
MessageBox.Show("The file you entered does not exist.");
return;
}
// load the image....
}
For me, it's better to write it this way..
string file = this.cnicloc_txt.Text.Trim();
if (!string.IsNullOrEmpty(file))
{
byte[] imageBt = null;
FileStream fstream = new FileStream(file, FileMode.Open,
FileAccess.Read);
BinaryReader br = new BinaryReader(fstream);
imageBt = br.ReadBytes((int)fstream.Length);
}

Opening a File in C# using FileStream

I am trying to open a Binary file that I plan on converting to hex but I am running into issues with reading the file via FileStream,
private void button1_Click(object sender, EventArgs e)
{
openFD.Title = "Insert a BIN file";
openFD.InitialDirectory = "C:"; // Chooses the default location to open the file
openFD.FileName = " "; // Iniitalizes the File name
openFD.Filter = "Binary File|*.bin|Text File|*.txt"; // FIlters the types of files allowed to by chosen
if (openFD.ShowDialog() != DialogResult.Cancel)
{
chosenFile = openFD.FileName;
string directoryPath = Path.GetDirectoryName(chosenFile); // Returns the directory and the file name to reference the file
string dirName = System.IO.Path.GetDirectoryName(openFD.FileName); // Returns the proper directory with which to refernce the file
richTextBox1.Text += dirName;
richTextBox1.Text += chosenFile;
FileStream InputBin = new FileStream(
directoryPath, FileMode.Open, FileAccess.Read, FileShare.None);
}
}
I am receiving an error saying that the access to the path is denied, any ideas?
Now that I have gotten that error taken care of I have ran into another Issue, I can read the binary file, but I want to display it as a Hex file, I'm not sure what I am doing wrong but I'm not getting an output in HEX, it seems to be Int values...
if (openFD.ShowDialog() != DialogResult.Cancel)
{
chosenFile = openFD.FileName;
string directoryPath = Path.GetDirectoryName(chosenFile);
string dirName = System.IO.Path.GetDirectoryName(openFD.FileName);
using (FileStream stream = new FileStream(chosenFile, FileMode.Open, FileAccess.Read))
{
size = (int)stream.Length;
data = new byte[size];
stream.Read(data, 0, size);
}
while (printCount < size)
{
richTextBox1.Text += data[printCount];
printCount++;
}
Your code is miscommented
string directoryPath = Path.GetDirectoryName(chosenFile); // Returns the directory and the file name to reference the file
is not the filename, it's the directory path. You want:
FileStream InputBin = new FileStream(chosenFile, FileMode.Open,FileAccess.Read, FileShare.None);
Addtionally, if I were to guess based on your intentions, you should update your full function to be:
private void button1_Click(object sender, EventArgs e)
{
openFD.Title = "Insert a BIN file";
openFD.InitialDirectory = "C:"; // Chooses the default location to open the file
openFD.FileName = " "; // Iniitalizes the File name
openFD.Filter = "Binary File|*.bin|Text File|*.txt"; // FIlters the types of files allowed to by chosen
if (openFD.ShowDialog() != DialogResult.Cancel)
{
chosenFile = openFD.FileName;
richTextBox1.Text += chosenFile; //You may want to replace this with = unless you mean to append something that is already there.
FileStream InputBin = new FileStream(chosenFile, FileMode.Open,FileAccess.Read, FileShare.None);
}
}
To answer your second quesiton:
I am receiving an error saying that the access to the path is denied,
any ideas?
Now that I have gotten that error taken care of I have ran into
another Issue, I can read the binary file, but I want to display it as
a Hex file, I'm not sure what I am doing wrong but I'm not getting an
output in HEX, it seems to be Int values...
Modify to use string.Format:
if (openFD.ShowDialog() != DialogResult.Cancel)
{
chosenFile = openFD.FileName;
string directoryPath = Path.GetDirectoryName(chosenFile);
string dirName = System.IO.Path.GetDirectoryName(openFD.FileName);
using (FileStream stream = new FileStream(chosenFile, FileMode.Open, FileAccess.Read))
{
size = (int)stream.Length;
data = new byte[size];
stream.Read(data, 0, size);
}
while (printCount < size)
{
richTextBox1.Text += string.Format( "{0:X} ", data[printCount];
printCount++;
}
}
I've included an ideone example.

Writing to isolated storage in windows phone 7

I am trying to read from the isolated storage if the file is exist it will delete the whole file and directories before recreating the file.
Then if the file does not exist it will create the file and directories.
Below is my code: I got a error of opertion not permitted on isolated storage at write file
int indexQues;
string rate;
string[] queSplit;
string[] rateSplit;
private void saveBtn_Click(object sender, RoutedEventArgs e)
{
indexQues = queListPicker.SelectedIndex;
rate = rateListPicker.SelectedItem.ToString();
IsolatedStorageFile myStore = IsolatedStorageFile.GetUserStoreForApplication();
try
{
//For question
StreamReader readFileQue = new StreamReader(new IsolatedStorageFileStream("SettingFolder\\queSetting.txt", FileMode.Open, myStore));
//For passing rate
StreamReader readFileRate = new StreamReader(new IsolatedStorageFileStream("SettingFolder\\queSetting.txt", FileMode.Open, myStore));
String queText = readFileQue.ReadLine();
queSplit = queText.Split(new char[] { '^' });
String rateText = readFileRate.ReadLine();
rateSplit = rateText.Split(new char[] { '^' });
readFileQue.Close();
readFileRate.Close();
int noOfQueInDB = queSplit.Count();
int noOfRateInDB = rateSplit.Count();
MessageBox.Show(noOfQueInDB.ToString());
//if (noOfQueInDB == 2)
//{
myStore.DeleteFile("SettingFolder\\queSetting.txt");
myStore.DeleteFile("SettingFolder\\rateSetting.txt");
myStore.DeleteDirectory("SettingFolder");
MessageBox.Show("Deleted all");
myStore.CreateDirectory("SettingFolder");
//Retrieve the content of "noOfQues"
//And write it into queSetting.txt
StreamWriter writeFile = new StreamWriter(new IsolatedStorageFileStream("SettingFolder\\queSetting.txt", FileMode.Create, myStore));
writeFile.Write(indexQues);
// writeFile.Write("^" + indexQues);
writeFile.Close();
StreamWriter writeFile1 = new StreamWriter(new IsolatedStorageFileStream("SettingFolder\\rateSetting.txt", FileMode.Create, myStore));
writeFile1.Write(rate);
writeFile1.Close();
MessageBox.Show("Setting Saved");
MessageBox.Show(indexQues.ToString());
MessageBox.Show(rate);
NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
//}
}
catch (Exception)
{
myStore.CreateDirectory("SettingFolder");
//Retrieve the content of "noOfQues"
//And write it into queSetting.txt
// ****
// **** The following line throws an exception
// ****
StreamWriter writeFile = new StreamWriter(new IsolatedStorageFileStream("SettingFolder\\queSetting.txt", FileMode.Create, myStore));
writeFile.Write(indexQues);
// writeFile.Write("^" + indexQues);
writeFile.Close();
StreamWriter writeFile1 = new StreamWriter(new IsolatedStorageFileStream("SettingFolder\\rateSetting.txt", FileMode.Create, myStore));
writeFile1.Write(rate);
writeFile1.Close();
MessageBox.Show("Setting Saved");
MessageBox.Show(indexQues.ToString());
MessageBox.Show(rate);
NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
}
}
one point - this seems wrong (you open the same file twice ?):
//For question
StreamReader readFileQue = new StreamReader(new IsolatedStorageFileStream("SettingFolder\\queSetting.txt", FileMode.Open, myStore));
//For passing rate
StreamReader readFileRate = new StreamReader(new IsolatedStorageFileStream("SettingFolder\\queSetting.txt", FileMode.Open, myStore));
second point - you should use Dispose:
readFileQue.Close(); readFileQue.Dispose(); readFileQue = null;
readFileRate.Close(); readFileRate.Dispose(); readFileRate = null;
third point - user proper FileAccess when creating the files:
StreamWriter writeFile = new StreamWriter(new IsolatedStorageFileStream("SettingFolder\\rateSetting.txt",
FileMode.Create,
FileAccess.Write,
FileShare.Write,
myStore);
Hope the above helps... if not check whether the Directory is really created...
EDIT:
Are you sure the Exception is thrown from the catch-block ? IF so, then there must have happened some Exception before that - what was that Exception?

Categories

Resources