Archive for the ‘File Operations’ Category

Today’s post is a small code snippet for you to write byte array to an xml file using FileStream and Binary Writer class’s Write method.Hope this helps 🙂

private void ByteArrayToFile(string fileName, byte[] byteArray)
{
FileStream fs = new FileStream(fileName + ".xml", FileMode.Create, FileAccess.ReadWrite);
BinaryWriter bw = new BinaryWriter(fs, Encoding.Unicode);
bw.Write(byteArray);
bw.Close();
fs.Close();
}

I came across this error “Could not find a part of the path” while copying a file from one location to another.It threw exception at the second parameter of this below line

File.Copy(Path,FilePath + @"\" +FileName, true);

Value expected for this second parameter was like this C:\Templates\ANUTESTCODE11\test.xml where the test.xml gets added from the value of FileName.At one particulat section of calling code,the FileName was null & It was reading as C:\Templates\ANUTESTCODE11\ which resulted in the error message “Could not find a part of the path”

I found this during unit testing & this scenario has to be handled in the code.You should not give a chance for your code to fail & the appropriate way of using File.Copy is as below.This code snippet was suggested by one of the readers & adding it here.


try
{ if (!string.IsNullOrEmpty(FileName))
{ string newPath = System.IO.Path.Combine(FilePath, FileName);
if (File.Exists(Path) && Path.ToLower() != newPath.ToLower())
{
File.Copy(Path, newPath, true);

}
}
}
catch (Exception ex){ // handle the exception as desired}

It took sometime to figure out what went wrong when I was getting an Unauthorized Access Exception when trying to delete folder from C#.

UnAuthorizedAcess Exception when trying to delete a folder

There was a misleading factor that the folder was residing on our server & had an impression that authorization is not given to do so.I started thinking from a code perspective,when I could delete the folder manually & later via code when I manually changed the readonly attribute to false. So the problem was that readonly attribute gets set by itself while folder/file is getting created or copied via code hence it will not let you delete unless you remove the attributes.

I am adding the code snippet to delete the folder with the comments herewith

public void RemoveFolder(string[] FolderNames)
{
//Gets Path from web.config
string Path = ConfigurationManager.AppSettings[“Root”];
//Loops through all the folder names & form the DirectoryInfo Path
FolderNames.ToList().ForEach(foldername =>
{

DirectoryInfo Folder = new DirectoryInfo(Path + @”\” + foldername.Trim());
//Checks if folder exists in the Path provided
if (Folder.Exists)
{
//Sets attributes for the DirectoryInfo
Folder.Attributes = Folder.Attributes & ~System.IO.FileAttributes.ReadOnly;
//Gets all files inside the folder
FileInfo[] files = Folder.GetFiles();
//For each file,set the attributes so that it does not throw
//unauthorized access exception while trying to delete
Array.ForEach<FileInfo>(files, new Action<FileInfo>(
                            f =>
                            {
                                File.SetAttributes(f.FullName, FileAttributes.Normal);
                            }));

Folder.Delete(true);

}
});
}

Hope you find this post useful 🙂