it seems to be a rare Issue where i am not able to save the text file data strpath="c:\path\1234\abcd.txt";
here file is getting cretaed but the data which is there in the file is not getting saved .
if i check by Byte b length is shows 121.
public int SaveFile(byte[] b,string lstrpath)
{
FileStream fs = new FileStream(strpath,FileMode.Create);
fs.Write(b,0,b.Length);
fs.Close();
if(File.Exists(strpath))
开发者_高级运维 {
return 1;
}
else
{
return 0;
}
}
is there anything that i am going wrong here?
You are not disposing and flushing the stream. Because of this if an exception occurs you program will be leaking a file handle. Try this instead:
public void SaveFile(byte[] b,string lstrpath)
{
File.WriteAllBytes(lstrpath, b);
}
which now kind of defeats the purpose of the SaveFile
method as it is already built into the BCL.
Do a Flush() before closing. That is fs.Flush();
Could be a few things, surely? You don't check if the file exists already. You don't check if the directory exists. You don't check your file system permissions. Any one of those could cause it to fail.
Also, when you say fail, what do you mean? Do you get an exception? An error? Does it return 0 or 1? Does it fail silently? Does the file get created empty?
You need some error handling here too, which would have the double benefit of telling you where the error occurs and hopefully some more information about it.
The other answers are all valid (exception handling, dispose, ...), you might even want to use the using
statement. I'd go with Darin Dimitrovs answer, which makes your code much more simple and easier to read.
As for your question: How are you calling this method? This works for me in a simple console application:
class Program
{
static void Main(string[] args)
{
var text = "abcd";
var encoding = new UTF8Encoding();
var bytes = encoding.GetBytes(text);
SaveFile(bytes, @"D:\test.txt");
}
public static int SaveFile(byte[] b, string strpath)
{
FileStream fs = new FileStream(strpath, FileMode.Create);
fs.Write(b, 0, b.Length);
fs.Close();
if (File.Exists(strpath))
{
return 1;
}
else
{
return 0;
}
}
}
Notice I am using the exact same method. It works for me everytime, so the file can already exist. In your case, you might not be passing a string? Maybe a problem with the encoding?
精彩评论