C# Empty path name is not legal - Winform - c#

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.

Related

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

System.IO.MemoryStream cannot access a closed file

I'm new to Streams and in the program i'm developing requires reading data from a hex file.
File=level.dat
The code im using:
FileStream fs;
private void Form1_Load(object sender, EventArgs e)
{
Main("PCWorld\\level.dat");
NbtTree nbtTree = new NbtTree();
Stream s = fs;
Stream destStream = new MemoryStream();
nbtTree.ReadFrom(s);
nbtTree.WriteTo(destStream);
}
void Main():
void Main(string filename)
{
// From MSDN Forums, slightly modified by me
try
{
string fileName = filename;
// Create random data to write to the file.
byte[] dataArray = new byte[100000];
new Random().NextBytes(dataArray);
using (FileStream
fileStream = new FileStream(fileName, FileMode.Create))
{
// Write the data to the file, byte by byte.
for (int i = 0; i < dataArray.Length; i++)
{
fileStream.WriteByte(dataArray[i]);
}
// Set the stream position to the beginning of the file.
fileStream.Seek(0, SeekOrigin.Begin);
// Read and verify the data.
for (int i = 0; i < fileStream.Length; i++)
{
if (dataArray[i] != fileStream.ReadByte())
{
MessageBox.Show("Failed to load " + fileName + " (MCPC.dll)\n\nReason: Failed to read bytes\nResult: Close();\nSoloution: Try again and/or tell DMP9 Software", "Error");
Close();
return;
}
fs = fileStream;
}
}
}
catch (OutOfMemoryException ex)
{
MessageBox.Show("Failed to load NBT++.PC.exe\n\nReason: Out of memory (System.OutOfMemoryException: " + ex.Message + ")\nResult: Close();\nSoloution: Your PC Does not have enough RAM to run NBT++", "Error");
Close();
}
}
My program has a reference of Substrate (https://code.google.com/p/substrate-minecraft/downloads/list) and that does most of the work, but its my code giving
the "Cannot access a closed file"
Any help?
Thanks...
Your problem is in:
Stream s = fs;
The fs filestream is closed in your Main method (using statement disposes the filestream). To fix this you should open a new filestream to read from the file:
Stream s = new FileStream("PCWorld\\level.dat", FileMode.Read);
When using
using (FileStream fileStream = new FileStream(fileName, FileMode.Create))
{...}
you are closing this filestream when you go out scope. So you have to re-open file to read
http://msdn.microsoft.com/en-us/library/yh598w02.aspx

FileMode and FileAccess and IOException: The process cannot access the file 'filename' because it is being used by another process

I have an application A that generates a text file for tracing.
While, an application B needs read the same text file and attach in a mailmessage.
But I get the following error, when application B try read the text file:
IOException: The process cannot access the file 'filename' because it
is being used by another process
Any suggestions ? Maybe better use for FileMode and FileAccess?
Application A
if (File.Exists(nFile2)) File.Delete(nFile2);
traceFile2 = File.Open(nFile2, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);
if (traceFile2 != null)
{
var twt2 = new TextWriterTraceListener(traceFile2);
// http://www.helixoft.com/blog/archives/20
try
{
if (twt2.Writer is StreamWriter)
{
(twt2.Writer as StreamWriter).AutoFlush = true;
}
}
catch { }
var indiceTraceFile2 = Trace.Listeners.Add(twt2);
System.Diagnostics.Trace.WriteLine("INICIO: " + DateTime.Now.ToString());
Application B
using (FileStream fileStream = File.Open(f, FileMode.Open, FileAccess.ReadWrite, FileShare.Read))
{
var messageAttachment = new Attachment(fileStream, Path.GetFileName(f));
msgMail.Attachments.Add(messageAttachment);
}
You need to make sure that both the service and the reader open the log file non-exclusively. Notice line 2 of App A and Line 1 of App B
Application A:
if (File.Exists(nFile2))
File.Delete(nFile2);
traceFile2 = new FileStream(nFile2, FileMode.Open, FileAccess.Write, FileShare.ReadWrite);
if (traceFile2 != null)
{
var twt2 = new TextWriterTraceListener(traceFile2);
// http://www.helixoft.com/blog/archives/20
try
{
if (twt2.Writer is StreamWriter)
{
(twt2.Writer as StreamWriter).AutoFlush = true;
}
}
catch { }
var indiceTraceFile2 = Trace.Listeners.Add(twt2);
System.Diagnostics.Trace.WriteLine("INICIO: " + DateTime.Now.ToString());
and Application B:
using (FileStream fileStream = new FileStream(f, FileMode.Open,
FileAccess.Read,
FileShare.ReadWrite))
{
var messageAttachment = new Attachment(fileStream, Path.GetFileName(f));
msgMail.Attachments.Add(messageAttachment);
}
Of course you can read and write from/to the same file at the same time (by different threads/processes).
Here is a sample code. Just see how FileStream is created.
string fname = "a.txt";
//WRITER
Task.Factory.StartNew(() =>
{
var f = new FileStream(fname, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite);
var s = new StreamWriter(f);
long l = 0;
while (true)
{
s.WriteLine(l++);
s.Flush();
Task.Delay(1000).Wait();
}
});
//READER
Task.Factory.StartNew(() =>
{
Task.Delay(1000).Wait();
var f = new FileStream(fname, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
var s = new StreamReader(f);
while (true)
{
var line = s.ReadLine();
if (line == null) { Task.Delay(100).Wait(); continue; };
Console.WriteLine("> " + line + " <");
}
});
It seems that you are not using the Dispose() and Close() methods of StreamWriter class to release the file.
You need to release control of the file from Program A. Try closing or disposing the streamwriter when you finish.
Or you might attempt using as is described in the answer to this question: Releasing access to files

Empty path name is not legal Error

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

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