Working with Files and Directories

Started by
8 comments, last by bigjoe11a 15 years, 11 months ago
1) How can I find out in my code is a directory exists String RootPath = Path.Default.BBSRootPath; String FilesPath = Path.Default.FilesPath; The 1st one is my programs root directory and the 2nd one is the directory that I want to know if it exists. and if it doesn't, Then create it. 2) Is there tutorials on working with Binary Creating, Edited, Adding, Changing and deleting content from them.
Advertisement
What programming language?
Sorry, VC# 2008

Hi,

If you want to Check / Create a directory then you could do the following: Check if the directory exists and if not, create it like this:

if(!Directory.Exists(Path.Default.FilesPath))    Directory.CreateDirectory(Path.Default.FilesPath);


However, I think if you read the MSDN documentation, CreateDirectory can be used on its own - if the directory is there it does nothing, if its not it'll create it.

If you want tutorials on working with Binary files and file IO, the MSDN has loads of documentation.

Hope that helps,

James
Hi

I usually use XML to serialize stuff but it is just as easy to save binary.

I create a class with the settings I want to save, then use the Serializable Attribute on that class...

This might help...

Something like:

[Serializable()]
public class MySettings {

string mySetting;

// this will be serialized
public string MySetting { set { myString = value; } get { return myString; } }

}

Then when you want to save it...

// just a test object
MySettings obj = new MySettings();

obj.MySetting = "a string to save";

Stream stream = File.Open("yourFile.dat", FileMode.Create);
BinaryFormatter formatter = new BinaryFormatter();

formatter.Serialize(stream, obj);

I haven't tested this code! :
Ta

JT
Please take a moment to read my blog: :D
Quote:Original post by JamesLewis
Hi,

If you want to Check / Create a directory then you could do the following: Check if the directory exists and if not, create it like this:

*** Source Snippet Removed ***

However, I think if you read the MSDN documentation, CreateDirectory can be used on its own - if the directory is there it does nothing, if its not it'll create it.

If you want tutorials on working with Binary files and file IO, the MSDN has loads of documentation.

Hope that helps,

James


James, Thanks. One question. In what directory will it create the directory in.

if(!Directory.Exists(Path.Default.FilesPath))
Directory.CreateDirectory(Path.Default.FilesPath);
If this creates a directory would this create a directory in the programs root.


if(!Directory.Exists(Path.Defaault.BBSRootPath Path.Default.FilesPath))
Directory.CreateDirectory(Path.Defaault.BBSRootPath Path.Default.FilesPath);

I just wanted to make sure that the directory was created in the right place.






Quote:Original post by marraboy
Hi

I usually use XML to serialize stuff but it is just as easy to save binary.

I create a class with the settings I want to save, then use the Serializable Attribute on that class...

This might help...

Something like:

[Serializable()]
public class MySettings {

string mySetting;

// this will be serialized
public string MySetting { set { myString = value; } get { return myString; } }

}

Then when you want to save it...

// just a test object
MySettings obj = new MySettings();

obj.MySetting = "a string to save";

Stream stream = File.Open("yourFile.dat", FileMode.Create);
BinaryFormatter formatter = new BinaryFormatter();

formatter.Serialize(stream, obj);

I haven't tested this code! :
Ta

JT


Thanks JT, Its just that I'm lost. Any chance you can make it simple. The problem that I have is that I have to tie to binary files together.

The first file will setup some some thing like a Category. Then the 2nd Binary File will hold the Category Subs will all the information needed to access the directories. If you get my meaning.

Any way this is a project that I'm not going to be able to complete any way. I just was playing around with the code to see if I can do this.

Thanks
Hi

I'm working from memory so there may be slight errors but I would do something like (I think this is what you mean):

[Serializable()]
public class Categories {

System.Collections.Hashtable categorySubs;

// this will be serialized
public string CategorySubs { set { categorySubs = value; } get { return categorySubs; } }

}

You would have to have a class to store the category subs in there.

CategorySub sub = new CategorySub();

// config object here

categoriesInstance.CategorySubs.Add(someID, sub);


This of course saves everything in a single binary file. I'm not sure if this is what you want. Let me know otherwise.

Ta

JT
Please take a moment to read my blog: :D
Quote:
The problem that I have is that I have to tie to binary files together.

The first file will setup some some thing like a Category. Then the 2nd Binary File will hold the Category Subs will all the information needed to access the directories. If you get my meaning.


I'm not sure if I understand you here - you have to tie 2 binary files together? Can you explain why it is that you require 2 binary files - I'm being slow and can't follow your post!

Anyway, I personally like implementing ISerializable to quickly read / write files from / to disk in binary (I also think this is the standard for this type of operation?). So the following example is an object that implements ISerializable:

[Serializable()]public class MySerializableObject : ISerializable{        #region Some Properties To Be Serialized        // A string property        public string SomeString{ get; set; }        // A List property        public List<object> SomeList{ get; set; }        #endregion        #region Constructors        // Default constructor        public MySerializableObject        {        }        // Consrtuctor used when deserializing the object        public MySerializableObject(SerializationInfo info, StreamingContext context)        {            // Read the properties in from the serialization info list            this.SomeString = (string)info.GetValue(string.Format("SomeString"), typeof(string));            this.SomeList = (List<object>)info.GetValue(string.Format("SomeList"), typeof(List<object>));        }        #endregion        #region ISerializable Members        // Method used when serializing the object        public void GetObjectData(SerializationInfo info, StreamingContext context)        {            // Add the values of the properties to the serialization info list            info.AddValue(string.Format("SomeString"), this.SomeString);            info.AddValue(string.Format("SomeList"), this.SomeList);        }        #endregion}


The two important parts of that class are the GetObjectData method and the special constructor that takes a SerializationInfo and StreamingContext as arguments - these are used when serializing / deserializing the objects data.

Now you need some methods that read / write the data from / to binary files. The following code is for writting the data to disk using a Binary Serializer:

	/// <summary>	/// Serialises an object to a binary file.	/// </summary>        /// <param name="value">Object to be serialized.</param>        /// <param name="fullFileName">File name of the file ro serialise to.</param>        public static void SerializeBinary(object value, string fullFileName)        {            // Create a new filestream and initialise to null.            Stream fileStream = null;            // Try to serialize the data            try            {                // Try to create the directory if its not there		Directory.CreateDirectory(System.IO.Path.GetDirectoryName(fullFileName));                // Create a filestream and name the file the object will go into                 fileStream = File.Open(fullFileName, FileMode.Create, FileAccess.ReadWrite, FileShare.Delete);                // Create binary formatter to serialise the data                BinaryFormatter binaryFormatter = new BinaryFormatter();                // Serialise the data                binaryFormatter.Serialize(fileStream, value);            }            // Always clean up the stream after finishing the method            finally            {                // Check for null on the filestream                if (fileStream != null)                {                    // Flush and close the filestream                    fileStream.Flush();                    fileStream.Close();                }            }        }


That above method is a generic one I use sometimes and should work for any object that implements ISerializable correctly. The following method is for deserializing the data into the example object I provided in the first code snippet:

        /// <summary>	/// Deserialises a MySerializableObject object from a binary file.        /// </summary>        /// <param name="fullFileName">The file name of the file to deserialise from.</param>	/// <returns>A new MySerializableObject object populated from the file.</returns>        public static MySerializableObject DeserializeBinary(string fullFileName)        {            // Create an object to return            MySerializableObject newReadData = null;            // Create a filestream and a binary formatter            Stream fileStream = null;            BinaryFormatter binaryFormatter = new BinaryFormatter();            // Try to deserialize the data            try            {                // Open the file exclusively                fileStream = File.Open(fullFileName, FileMode.Open, FileAccess.Read, FileShare.None);                // Deserialize into a MySerializableObject object                newReadData = (MySerializableObject)binaryFormatter.Deserialize(fileStream);            }            // Always close the streams when finished            finally            {                // Close the streams		if(fileStream != null)		    fileStream.Close();            }            // Return the object - returns null if something went wrong            return newReadData;        }


Hope that helps,

James


EDIT: I really would strongly advise you to take a look at the MSDN documentation - there are loads of examples on manipulating files (XML / Binary etc) on there.
Quote:Original post by JamesLewis
Quote:
The problem that I have is that I have to tie to binary files together.

The first file will setup some some thing like a Category. Then the 2nd Binary File will hold the Category Subs will all the information needed to access the directories. If you get my meaning.


I'm not sure if I understand you here - you have to tie 2 binary files together? Can you explain why it is that you require 2 binary files - I'm being slow and can't follow your post!

Anyway, I personally like implementing ISerializable to quickly read / write files from / to disk in binary (I also think this is the standard for this type of operation?). So the following example is an object that implements ISerializable:

*** Source Snippet Removed ***

The two important parts of that class are the GetObjectData method and the special constructor that takes a SerializationInfo and StreamingContext as arguments - these are used when serializing / deserializing the objects data.

Now you need some methods that read / write the data from / to binary files. The following code is for writting the data to disk using a Binary Serializer:

*** Source Snippet Removed ***

That above method is a generic one I use sometimes and should work for any object that implements ISerializable correctly. The following method is for deserializing the data into the example object I provided in the first code snippet:

*** Source Snippet Removed ***

Hope that helps,

James


EDIT: I really would strongly advise you to take a look at the MSDN documentation - there are loads of examples on manipulating files (XML / Binary etc) on there.


James, Thanks you have me all so lost. I guess it doesn't matter any way. I'm not going to be able to complete my project any way. I just wanted to see if there was more I could learn and well thats way over my head.

---------------------
I'm not sure if I understand you here - you have to tie 2 binary files together? Can you explain why it is that you require 2 binary files - I'm being slow and can't follow your post!
---------------------

To answer your question. I don't know. See the project requires access too files files the drive, The full project. Is a Telnet, Mail and a web server with a BBS. At my age I just don't think I'm going to be able to learn all this. Its just that I have a dream.

No big deal and thanks for your help

Joe

This topic is closed to new replies.

Advertisement