How do you serialize a FileInfo object in WinForms or WPF? The basic issue is FileInfo doesn't have a parameterless constructor, which is required by XmlSerializer. While there are other ways to accomplish this task, the simplest way is to create a basic wrapper around FileInfo.
Create a Serializable FileInfo class
FileInfoSerializable.cs
using System; using System.IO; namespace Utilities { /// <summary> /// Serializable wrapper for FileInfo. /// </summary> public class FileInfoSerializable { #region ~~~ Fields ~~~ private readonly FileInfo _fileInfo; #endregion #region ~~~ Constructors ~~~ // A parameterless constructor is required for serialization public FileInfoSerializable() { _fileInfo = new FileInfo("export.xml"); } public FileInfoSerializable(string FileName) { _fileInfo = new FileInfo(FileName); } public FileInfoSerializable(FileInfo FileInfo) { _fileInfo = FileInfo; } #endregion #region ~~~ Properties ~~~ public string Name { get { return _fileInfo.Name; } set {} } public string FullName { get { return _fileInfo.FullName; } set {} } public long Length { get { return _fileInfo.Length; } set {} } public string Extension { get { return _fileInfo.Extension; } set {} } public DateTime CreationTime { get { return _fileInfo.CreationTime; } set {} } public DateTime LastWriteTime { get { return _fileInfo.LastWriteTime; } set {} } public string DirectoryName { get { return _fileInfo.DirectoryName; } set {} } #endregion } }
No comments:
Post a Comment