xtd 0.2.0
Loading...
Searching...
No Matches
xtd::io::file_info Class Reference
Inheritance diagram for xtd::io::file_info:
xtd::io::file_system_info xtd::abstract_object xtd::object

Definition

Provides static methods for the creation, copying, deletion, moving, and opening of files, and aids in the creation of std::fstream objects.

Provides static methods for the creation, copying, deletion, moving, and opening of files,...
Definition file_info.h:39
Provides the base class for both xtd::io::file_info and xtd::io::directory_info objects.
Definition file_system_info.h:85
#define core_export_
Define shared library export.
Definition core_export.h:13
Inheritance
xtd::io::file_system_infoxtd::io::file_info
Header
#include <xtd/io/file_info>
Namespace
xtd::io
Library
xtd.core
Examples
The following example demonstrates some of the main members of the xtd::io::file_info class. When the properties are first retrieved, xtd::io::file_info calls the xtd::io::file_info::refresh method and caches information about the file. On subsequent calls, you must call xtd::io::file_info::refresh to get the latest copy of the information.
#include <xtd/io/file_info>
#include <xtd/io/path>
#include <xtd/console>
#include <xtd/startup>
#include <xtd/using>
using namespace xtd;
using namespace xtd::io;
class program {
public:
static auto main() {
auto path = path::get_temp_file_name();
// Create a file to write to.
using_(auto sw = fi1.create_text()) {
sw.write_line("Hello");
sw.write_line("And");
sw.write_line("Welcome");
}
// Open the file to read from.
using_(auto sr = fi1.open_text()) {
while (!sr.end_of_stream())
console::write_line(sr.read_line());
}
try {
auto path2 = path::get_temp_file_name();
file_info fi2(path2);
// Ensure that the target does not exist.
fi2.remove();
// Copy the file.
fi1.copy_to(path2);
console::write_line("{} was copied to {}.", path, path2);
// Delete the newly created file.
fi2.remove();
console::write_line("{} was successfully deleted.", path2);
} catch (const system_exception& e) {
console::write_line("The process failed: {}", e.to_string());
}
}
};
startup_(program::main);
// This code produces the following output :
// Hello
// And
// Welcome
// /var/folders/d5/k7mxnq214dxf3jbvvvhpbfqh0000gn/T/tmp99dcece9.tmp was copied to /var/folders/d5/k7mxnq214dxf3jbvvvhpbfqh0000gn/T/tmp235be07d.tmp.
// /var/folders/d5/k7mxnq214dxf3jbvvvhpbfqh0000gn/T/tmp235be07d.tmp was successfully deleted.
Performs operations on std::basic_string instances that contain file or directory path information....
Definition path.h:34
Defines the base class for predefined exceptions in the xtd namespace.
Definition system_exception.h:25
#define startup_(main_method)
Defines the entry point to be called when the application loads. Generally this is set either to the ...
Definition startup.h:166
#define using_(...)
The specified expression is cleared automatically when the scope is ended.
Definition using.h:33
The xtd::io namespace contains types that allow reading and writing to files and data streams,...
Definition binary_reader.h:16
The xtd namespace contains all fundamental classes to access Hardware, Os, System,...
Definition xtd_about_box.h:10
Remarks
Use the xtd::io::file_info class for typical operations such as copying, moving, renaming, creating, opening, deleting, and appending to files.
If you are performing multiple operations on the same file, it can be more efficient to use xtd::io::file_info instance methods instead of the corresponding static methods of thetd::io::file class, because a security check will not always be necessary.
Many of the xtd::io::file_info methods return other I/O types when you create or open files. You can use these other types to further manipulate a file. For more information, see specific xtd::io::file_info members such as xtd::io::file_info::open, xtd::io::file_info::open_read, xtd::io::file_info::open_text, xtd::io::file_info::create_text, or xtd::io::file_info::create.
By default, full read/write access to new files is granted to all users.
Examples
file_info.cpp, file_info2.cpp, file_info_append_text.cpp, file_info_move_to.cpp, file_info_open.cpp, file_info_open_read.cpp, file_info_open_text.cpp, file_info_open_write.cpp, and file_info_replace.cpp.

Public Fields

static const file_info empty
 Represents the uninitialized xtd::io::file_info object. This field is constant.
 

Public Constructors

 file_info (const xtd::ustring &file_name)
 Initializes a new instance of the xtd::io::file_info class, which acts as a wrapper for a file path.
 

Public Properties

xtd::io::directory_info directory () const
 Gets an instance of the parent directory.
 
xtd::ustring directory_name () const
 Gets a string representing the directory's full path.
 
bool exists () const override
 Gets a value indicating whether a file exists.
 
bool is_read_only () const
 Gets a value that determines if the current file is read only.
 
void is_read_only (bool value)
 Sets a value that determines if the current file is read only.
 
size_t length () const
 Gets the size, in bytes, of the current file.
 
xtd::ustring name () const override
 Gets the name of the file.
 

Public Methods

xtd::io::stream_writer append_text () const
 Creates a xtd::io::stream_writer that appends text to the file represented by this instance of the xtd::io::file_info.
 
xtd::io::file_info copy_to (const xtd::ustring &dest_file_name) const
 Copies an existing file to a new file, disallowing the overwriting of an existing file.
 
xtd::io::file_info copy_to (const xtd::ustring &dest_file_name, bool overwrite) const
 Copies an existing file to a new file, allowing the overwriting of an existing file.
 
std::ofstream create () const
 Creates a file.
 
xtd::io::stream_writer create_text () const
 Creates a std::ofstream that writes a new text file.
 
void move_to (const xtd::ustring &dest_file_name)
 Moves a specified file to a new location, providing the option to specify a new file name.
 
void move_to (const xtd::ustring &dest_file_name, bool overwrite)
 Moves a specified file to a new location, providing the options to specify a new file name and to overwrite the destination file if it already exists.
 
std::fstream open (std::ios::openmode mode) const
 Opens a file in the specified mode.
 
std::ifstream open_read () const
 Creates a read-only std::ifstream.
 
xtd::io::stream_reader open_text () const
 Creates a xtd::io::stream_reader that reads from an existing text file.
 
std::ofstream open_write () const
 Creates a write-only std::ofstream.
 
void remove () const override
 Permanently deletes a file.
 
file_info replace (const xtd::ustring &destination_file_name, const xtd::ustring &destination_backup_file_name)
 Replaces the contents of a specified file with the file described by the current xtd::io::file_info object, deleting the original file, and creating a backup of the replaced file.
 

Additional Inherited Members

- Public Member Functions inherited from xtd::io::file_system_info
xtd::io::file_attributes attributes () const
 Gets the attributes for the current file or directory.
 
xtd::io::file_system_infoattributes (xtd::io::file_attributes value)
 Sets the attributes for the current file or directory.
 
const xtd::date_timecreation_time () const
 Gets the creation time of the current file or directory.
 
xtd::io::file_system_infocreation_time (const xtd::date_time &value)
 Gets the creation time of the current file or directory.
 
xtd::date_time creation_time_utc () const
 Gets the creation time, in coordinated universal time (UTC), of the current file or directory.
 
xtd::io::file_system_infocreation_time_utc (const xtd::date_time &value)
 Sets the creation time, in coordinated universal time (UTC), of the current file or directory.
 
virtual xtd::ustring extension () const
 Gets the extension part of the file name, including the leading dot . even if it is the entire file name, or an empty string if no extension is present.
 
xtd::ustring full_name () const
 Gets the full path of the directory or file.
 
const xtd::date_timelast_access_time () const
 Gets the time the current file or directory was last accessed.
 
xtd::io::file_system_infolast_access_time (const xtd::date_time &value)
 Sets the time the current file or directory was last accessed.
 
xtd::date_time last_access_time_utc () const
 Gets the time, in coordinated universal time (UTC), that the current file or directory was last accessed.
 
xtd::io::file_system_infolast_access_time_utc (const xtd::date_time &value)
 Sets the time, in coordinated universal time (UTC), that the current file or directory was last accessed.
 
const xtd::date_timelast_write_time () const
 Gets the time when the current file or directory was last written to.
 
xtd::io::file_system_infolast_write_time (const xtd::date_time &value)
 Sets the time when the current file or directory was last written to.
 
xtd::date_time last_write_time_utc () const
 Gets the time, in coordinated universal time (UTC), when the current file or directory was last written to.
 
xtd::io::file_system_infolast_write_time_utc (const xtd::date_time &value)
 Sets the time, in coordinated universal time (UTC), when the current file or directory was last written to.
 
xtd::io::file_permissions permissions () const
 Gets the permissions for the current file or directory.
 
xtd::io::file_system_infopermissions (xtd::io::file_permissions value)
 Sets the permissions for the current file or directory.
 
void refresh ()
 Refreshes the state of the object.
 
xtd::ustring to_string () const noexcept override
 Returns the original path. Use the xtd::io::file_system_info::full_name or xtd::io::file_system_info::name properties for the full path or file/directory name.
 
- Public Member Functions inherited from xtd::object
 object ()=default
 Create a new instance of the ultimate base class object.
 
bool equals (const object &obj) const noexcept
 Determines whether the specified object is equal to the current object.
 
virtual size_t get_hash_code () const noexcept
 Serves as a hash function for a particular type.
 
virtual type_object get_type () const noexcept
 Gets the type of the current instance.
 
template<typename object_t >
std::unique_ptr< object_t > memberwise_clone () const noexcept
 Creates a shallow copy of the current object.
 
- Static Public Member Functions inherited from xtd::object
static bool equals (const object &object_a, const object &object_b) noexcept
 Determines whether the specified object instances are considered equal.
 
static bool reference_equals (const object &object_a, const object &object_b) noexcept
 Determines whether the specified object instances are the same instance.
 
- Protected Attributes inherited from xtd::io::file_system_info
xtd::ustring full_path_
 Represents the fully qualified path of the directory or file.
 
xtd::ustring original_path_
 The path originally specified by the user, whether relative or absolute.
 
- Protected Member Functions inherited from xtd::io::file_system_info
 file_system_info ()=default
 Initializes a new instance of the xtd::io::file_system_info class.
 
- Protected Member Functions inherited from xtd::abstract_object
 abstract_object ()=default
 Initializes a new instance of the xtd::abstract_object class.
 

Constructor & Destructor Documentation

◆ file_info()

xtd::io::file_info::file_info ( const xtd::ustring file_name)
explicit

Initializes a new instance of the xtd::io::file_info class, which acts as a wrapper for a file path.

Parameters
file_nameThe fully qualified name of the new file, or the relative file name. Do not end the path with the directory separator character.
Exceptions
xtd:argument_exceptionThe file name is empty, contains only white spaces, or contains invalid characters.
xtd::security::security_exceptionThe caller does not have the required permission.
xtd::unauthorized_access_exceptionAccess to fileName is denied.
xtd::io::path_too_long_exceptionThe specified path, file name, or both exceed the system-defined maximum length.
xtd::not_supported_exceptionfileName contains a colon (:) in the middle of the string.
Examples
The following example demonstrates some of the main members of the xtd::io::file_info class. When the properties are first retrieved, xtd::io::file_info calls the xtd::io::file_info::refresh method and caches information about the file. On subsequent calls, you must call xtd::io::file_info::refresh to get the latest copy of the information.
#include <xtd/io/file_info>
#include <xtd/io/path>
#include <xtd/console>
#include <xtd/startup>
#include <xtd/using>
using namespace xtd;
using namespace xtd::io;
class program {
public:
static auto main() {
auto path = path::get_temp_file_name();
// Create a file to write to.
using_(auto sw = fi1.create_text()) {
sw.write_line("Hello");
sw.write_line("And");
sw.write_line("Welcome");
}
// Open the file to read from.
using_(auto sr = fi1.open_text()) {
while (!sr.end_of_stream())
console::write_line(sr.read_line());
}
try {
auto path2 = path::get_temp_file_name();
file_info fi2(path2);
// Ensure that the target does not exist.
fi2.remove();
// Copy the file.
fi1.copy_to(path2);
console::write_line("{} was copied to {}.", path, path2);
// Delete the newly created file.
fi2.remove();
console::write_line("{} was successfully deleted.", path2);
} catch (const system_exception& e) {
console::write_line("The process failed: {}", e.to_string());
}
}
};
startup_(program::main);
// This code produces the following output :
// Hello
// And
// Welcome
// /var/folders/d5/k7mxnq214dxf3jbvvvhpbfqh0000gn/T/tmp99dcece9.tmp was copied to /var/folders/d5/k7mxnq214dxf3jbvvvhpbfqh0000gn/T/tmp235be07d.tmp.
// /var/folders/d5/k7mxnq214dxf3jbvvvhpbfqh0000gn/T/tmp235be07d.tmp was successfully deleted.
Remarks
You can specify either the fully qualified or the relative file name, but the security check gets the fully qualified name.

Member Function Documentation

◆ append_text()

xtd::io::stream_writer xtd::io::file_info::append_text ( ) const

Creates a xtd::io::stream_writer that appends text to the file represented by this instance of the xtd::io::file_info.

Returns
a new A new std::ofstream.
Examplle
The following example appends text to a file and reads from the file.
#include <xtd/io/file_info>
#include <xtd/io/path>
#include <xtd/console>
#include <xtd/startup>
#include <xtd/using>
using namespace xtd;
using namespace xtd::io;
class program {
public:
static auto main() {
auto fi = file_info {path::combine(path::get_temp_path(), "MyTest.txt")};
// This text is added only once to the file.
if (!fi.exists()) {
//Create a file to write to.
using_(auto sw = fi.create_text()) {
sw.write_line("Hello");
sw.write_line("And");
sw.write_line("Welcome");
}
}
// This text will always be added, making the file longer over time
// if it is not deleted.
using_(auto sw = fi.append_text()) {
sw.write_line("This");
sw.write_line("is Extra");
sw.write_line("Text");
}
//Open the file to read from.
using_(auto sr = fi.open_text()) {
while (!sr.end_of_stream())
console::write_line(sr.read_line());
}
}
};
startup_(program::main);
// This code produces output similar to the following;
// results may vary based on the computer/file structure/etc.:
//
// Hello
// And
// Welcome
// This
// is Extra
// Text
//When you run this application a second time, you will see the following output:
//
// Hello
// And
// Welcome
// This
// is Extra
// Text
// This
// is Extra
// Text
Examples
The following example demonstrates appending text to the end of a file and also displays the result of the append operation to the console. The first time this routine is called, the file is created if it does not exist. After that, the specified text is appended to the file.
#include <xtd/xtd>
using namespace std;
using namespace xtd;
using namespace xtd::io;
class program {
static auto main() {
file_info fi("temp.txt");
// Create a writer, ready to add entries to the file.
stream_writer sw = fi.append_text();
sw.write_line("Add as many lines as you like...");
sw.write_line("Add another line to the output...");
sw.flush();
sw.close();
// Get the information out of the file and display it.
// Remember that the file might have other lines if it already existed.
ifstream ifs(fi.open_read());
stream_reader sr(ifs);
while (sr.peek() != -1)
console::write_line(sr.read_line());
}
};
startup_(program::main);
// This code produces output similar to the following;
// results may vary based on the computer/file structure/etc.:
// Add as many lines as you like...
// Add another line to the output...
Implements a xtd::io::text_reader that reads characters from a byte stream.
Definition stream_reader.h:26
Implements a xtd::io::text_writer for writing characters to a stream.
Definition stream_writer.h:26
void flush() override
Clears all buffers for the current writer and causes any buffered data to be written to the underlyin...
void close() override
Closes the stream_writer object and the underlying stream, and releases any system resources associat...
void write_line()
Writes new line to the text stream.

◆ copy_to() [1/2]

xtd::io::file_info xtd::io::file_info::copy_to ( const xtd::ustring dest_file_name) const

Copies an existing file to a new file, disallowing the overwriting of an existing file.

Parameters
desy_file_nameThe name of the new file to copy to.
Returns
A new file with a fully qualified path.
Exceptions
xtd::argument_exceptiondest_file_name is empty, contains only white spaces, or contains invalid characters.
xtd::io_io_exceptionAn error occurs, or the destination file already exists and overwrite is false.
xtd::security::security_exceptionThe caller does not have the required permission.
xtd::io::directory_not_found_exceptionThe directory specified in dest_file_name does not exist.
xtd::unauthorized_access_exceptionAdirectory path is passed in, or the file is being moved to a different drive.
xtd::ioo::path_too_long_exceptionThe specified path, file name, or both exceed the system-defined maximum length.
xtd::not_supported_exceptiondest_file_name contains a colon (:) in the middle of the string.
Examples
The following example demonstrates both overloads of the xtd::io::file_info::copy_to method.
#include <xtd/xtd>
using namespace std;
using namespace xtd;
using namespace xtd::io;
class program {
public:
static auto main() {
ustring path = R"(c:\SoureFile.txt)";
ustring path2 = R"(c:\NewFile.txt)";
file_info fi2(path2);
try {
// Create the source file.
using_(ofstream s(fi1.create())) {
}
//Ensure that the target file does not exist.
if (file::exists(path2)) {
fi2.remove();
}
//Copy the file.f
fi1.copy_to(path2);
console::write_line("{0} was copied to {1}.", path, path2);
} catch (const io_exception& ioex) {
console::write_line(ioex.message());
}
}
};
startup_(program::main);
// This code produces output similar to the following;
// results may vary based on the computer/file structure/etc.:
// Add as many lines as you like...
// Add another line to the output...
The exception that is thrown when an I/O error occurs.
Definition io_exception.h:27
virtual const xtd::ustring & message() const noexcept
Gets message associate to the exception.
Represents text as a sequence of UTF-8 code units.
Definition ustring.h:47
@ s
The S key.
Examples
The following example demonstrates copying one file to another file, throwing an exception if the destination file already exists.
#include <xtd/xtd>
using namespace std;
using namespace xtd;
using namespace xtd::io;
class program {
public:
static auto main() {
try {
// Create a reference to a file, which might or might not exist.
// If it does not exist, it is not yet created.
file_info fi("temp.txt");
// Create a writer, ready to add entries to the file.
ofstream ofs(fi.append_text());
stream_writer sw(ofs);
sw.write_line("Add as many lines as you like...");
sw.write_line("Add another line to the output...");
sw.flush();
sw.close();
// Get the information out of the file and display it.
ifstream ifs(fi.open_read());
stream_reader sr(ifs);
console::write_line("This is the information in the first file:");
while (sr.peek() != -1)
console::write_line(sr.read_line());
// Copy this file to another file. The file will not be overwritten if it already exists.
file_info newfi = fi.copy_to("newTemp.txt");
// Get the information out of the new file and display it.
ifs = newfi.open_read();
sr = stream_reader(ifs);
console::write_line("{0}This is the information in the second file:", environment::new_line());
while (sr.peek() != -1)
console::write_line(sr.read_line());
} catch(const system_exception& e) {
console::write_line(e.message());
}
}
};
startup_(program::main);
// This code produces output similar to the following;
// results may vary based on the computer/file structure/etc.:
//
// This is the information in the first file:
// Add as many lines as you like...
// Add another line to the output...
// This is the information in the second file:
// Add as many lines as you like...
// Add another line to the output...
xtd::io::file_info copy_to(const xtd::ustring &dest_file_name) const
Copies an existing file to a new file, disallowing the overwriting of an existing file.
std::ifstream open_read() const
Creates a read-only std::ifstream.
@ e
The E key.
Remarks
Use the xtd::io::file_info::copy_to(ustring, bool) method to allow overwriting of an existing file.
Warning
Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior
Examples
file_info.cpp.

◆ copy_to() [2/2]

xtd::io::file_info xtd::io::file_info::copy_to ( const xtd::ustring dest_file_name,
bool  overwrite 
) const

Copies an existing file to a new file, allowing the overwriting of an existing file.

Parameters
dest_file_nameThe name of the new file to copy to.
overwritetrue to allow an existing file to be overwritten; otherwise, false.
Returns
A new file, or an overwrite of an existing file if overwrite is true. If the file exists and overwrite is false, an xtd::io::ioo_exception is thrown.
Exceptions
xtd::argument_exceptiondest_file_name is empty, contains only white spaces, or contains invalid characters.
xtd::io_io_exceptionAn error occurs, or the destination file already exists and overwrite is false.
xtd::security::security_exceptionThe caller does not have the required permission.
xtd::io::directory_not_found_exceptionThe directory specified in dest_file_name does not exist.
xtd::unauthorized_access_exceptionAdirectory path is passed in, or the file is being moved to a different drive.
xtd::ioo::path_too_long_exceptionThe specified path, file name, or both exceed the system-defined maximum length.
xtd::not_supported_exceptiondest_file_name contains a colon (:) in the middle of the string.
Examples
The following example demonstrates both overloads of the xtd::io::file_info::copy_to method.
#include <xtd/xtd>
using namespace std;
using namespace xtd;
using namespace xtd::io;
class program {
public:
static auto main() {
ustring path = R"(c:\SoureFile.txt)";
ustring path2 = R"(c:\NewFile.txt)";
file_info fi2(path2);
try {
// Create the source file.
using_(ofstream s(fi1.create())) {
}
//Ensure that the target file does not exist.
if (file::exists(path2)) {
fi2.remove();
}
//Copy the file.f
fi1.copy_to(path2);
console::write_line("{0} was copied to {1}.", path, path2);
} catch (const io_exception& ioex) {
console::write_line(ioex.message());
}
}
};
startup_(program::main);
// This code produces output similar to the following;
// results may vary based on the computer/file structure/etc.:
// Add as many lines as you like...
// Add another line to the output...
Examples
The following example demonstrates copying one file to another file, throwing an exception if the destination file already exists.
#include <xtd/xtd>
using namespace std;
using namespace xtd;
using namespace xtd::io;
class program {
public:
static auto main() {
// Create a reference to a file, which might or might not exist.
// If it does not exist, it is not yet created.
file_info fi("temp.txt");
// Create a writer, ready to add entries to the file.
ofstream ofs(fi.append_text());
stream_writer sw(ofs);
sw.write_line("Add as many lines as you like...");
sw.write_line("Add another line to the output...");
sw.flush();
sw.close();
// Get the information out of the file and display it.
ifstream ifs(fi.open_read());
stream_reader sr(ifs);
console::write_line("This is the information in the first file:");
while (sr.peek() != -1)
console::write_line(sr.read_line());
// Copy this file to another file. The true parameter specifies that the file will be overwritten if it already exists.
file_info newfi = fi.copy_to("newTemp.txt", true);
// Get the information out of the new file and display it.
ifs = newfi.open_read();
sr = stream_reader(ifs);
console::write_line("{0}This is the information in the second file:", environment::new_line());
while (sr.peek() != -1)
console::write_line(sr.read_line());
}
};
startup_(program::main);
// This code produces output similar to the following;
// results may vary based on the computer/file structure/etc.:
//
// This is the information in the first file:
// Add as many lines as you like...
// Add another line to the output...
// Add as many lines as you like...
// Add another line to the output...
// This is the information in the second file:
// Add as many lines as you like...
// Add another line to the output...
// Add as many lines as you like...
// Add another line to the output...
Remarks
Use this method to allow or prevent overwriting of an existing file. Use the xtd::io::file_info::copy_to(ustring) method to prevent overwriting of an existing file by default.
Warning
Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method. If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior

◆ create()

std::ofstream xtd::io::file_info::create ( ) const

Creates a file.

Returns
A new file.
Examples
The following example creates a reference to a file, and then creates the file on disk using xtd::io::file_info.create().
#include <xtd/xtd>
using namespace std;
using namespace xtd;
using namespace xtd::io;
class program {
public:
static auto main() {
// Create a reference to a file.
file_info fi("temp.txt");
// Actually create the file.
ofstream ofs( fi.create());
// Modify the file as required, and then close the file.
ofs.close();
// Delete the file.
fi.remove();
}
};
startup_(program::main);
Examples
The following example creates a file, adds some text to it, and reads from the file.
#include <xtd/io/file_info>
#include <xtd/io/stream_reader>
#include <xtd/io/stream_writer>
#include <xtd/console>
#include <xtd/startup>
#include <xtd/using>
using namespace std;
using namespace xtd;
using namespace xtd::io;
class program {
public:
static auto main() {
auto path = "MyTest.txt";
auto fi = file_info {path};
// Delete the file if it exists.
if (fi.exists())
fi.remove();
//Create the file.
using_(auto fs = fi.create()) {
auto sw = stream_writer {fs};
sw.write_line("This is some text in the file.");
}
//Open the stream and read it back.
using_(auto fs = fi.open(ios::in)) {
auto sr = stream_reader {fs};
while (!sr.end_of_stream())
console::write_line(sr.read_line());
}
}
};
startup_(program::main);
// This code produces the following output :
//
// This is some text in the file.
Remarks
By default, full read/write access to new files is granted to all users.
This method is a wrapper for the functionality provided by xtd::io::file::create.

◆ create_text()

xtd::io::stream_writer xtd::io::file_info::create_text ( ) const

Creates a std::ofstream that writes a new text file.

Returns
A new std::ofstream.
Exceptions
xtd::unauthorized_access_exceptionThe file name is a directory.
xtd::io::io_exceptionThe disk is read-only.
xtd::security::security_exceptionThe caller does not have the required permission.
Examples
The following example demonstrates the xtd::io::file_info::create_text method.
#include <xtd/io/file_info>
#include <xtd/io/path>
#include <xtd/console>
#include <xtd/startup>
#include <xtd/using>
using namespace xtd;
using namespace xtd::io;
class program {
public:
static auto main() {
auto path = path::combine(path::get_temp_path(), "MyTest.txt");
auto fi = file_info {path};
if (!fi.exists()) {
//Create a file to write to.
using_(auto sw = fi.create_text()) {
sw.write_line("Hello");
sw.write_line("And");
sw.write_line("Welcome");
}
}
//Open the file to read from.
using_(auto sr = fi.open_text()) {
while (!sr.end_of_stream())
console::write_line(sr.read_line());
}
}
};
startup_(program::main);
// This code produces output similar to the following;
// results may vary based on the computer/file structure/etc.:
//
// Hello
// And
// Welcome
Remarks
By default, full read/write access to new files is granted to all users.
Examples
file_info.cpp.

◆ directory()

xtd::io::directory_info xtd::io::file_info::directory ( ) const

Gets an instance of the parent directory.

Returns
A xtd::io::directory_info object representing the parent directory of this file.
Exceptions
xtd::io::directory_not_found_exceptionThe specified path is invalid, such as being on an unmapped drive.
xtd::security::security_exceptionThe caller does not have the required permission.
Examples
file_info_move_to.cpp.

◆ directory_name()

xtd::ustring xtd::io::file_info::directory_name ( ) const

Gets a string representing the directory's full path.

Returns
A string representing the directory's full path.
Exceptions
xtd::security::security_exceptionThe caller does not have the required permission.
xtd::io::path_too_long_exceptionThe specified path, file name, or both exceed the system-defined maximum length.
Exemple
The following example retrieves the full path of the specified file.
ustring file_name = R"(C:\TMP\log.txt)";
file_info file_info(file_name);
return;
console::write_line("{0} has a directoryName of {1}", file_name, file_info.directory_name());
/* This code produces output similar to the following,
* though actual results may vary by machine:
*
* C:\TMP\log.txt has a directory name of C:\TMP
*/
static void write_line()
Writes the current line terminator to the standard output stream using the specified format informati...
bool exists() const override
Gets a value indicating whether a file exists.
xtd::ustring directory_name() const
Gets a string representing the directory's full path.
Remarks
To get the parent directory as a xtd::io::directory_info object, use the xtd::io::file_info::directory property.
When first called, xtd::io::file_info calls xtd::io::file_info::refresh and caches information about the file. On subsequent calls, you must call xtd::io::file_info::refresh to get the latest copy of the information.

◆ exists()

bool xtd::io::file_info::exists ( ) const
overridevirtual

Gets a value indicating whether a file exists.

Returns
true if the file exists; false if the file does not exist or if the file is a directory.
Examples
The following code example uses the xtd::io::file_info::exists property ensure a file exists before opening it. You can use this technique to throw a custom exception when the file is not found.
std::vector<char> open_data_file(const ustring& file_name) {
// Check the FileName argument.
if (file_name.size() == 0)
throw argument_exception("file_name", csf_);
// Check to see if the file exists.
file_info f_info(file_name);
// You can throw a personalized exception if
// the file does not exist.
if (!f_info.exists())
throw file_not_found_exception("The file was not found.", csf_);
// Open the file.
std::ifstream f_stream(file_name, std::ios::binary);
// Create a buffer.
std::vector<char> buffer(f_info.size());
// Read the file contents to the buffer.
f_stream.read(&buffer[0], f_info.size());
// return the buffer.
return buffer;
}
The exception that is thrown when one of the arguments provided to a method is not valid.
Definition argument_exception.h:21
The exception that is thrown when an attempt to access a file that does not exist on disk fails.
Definition file_not_found_exception.h:27
#define csf_
Provides information about the current stack frame.
Definition current_stack_frame.h:30
Remarks
When first called, xtd::io::file_info calls xtd::io::file_info::refresh and caches information about the file. On subsequent calls, you must call xtd::io::file_info::refresh to get the latest copy of the information.
The xtd::io::file_info::exists property returns false if any error occurs while trying to determine if the specified file exists. This can occur in situations that raise exceptions such as passing a file name with invalid characters or too many characters, a failing or missing disk, or if the caller does not have permission to read the file.

Implements xtd::io::file_system_info.

Examples
file_info2.cpp, and file_info_move_to.cpp.

◆ is_read_only() [1/2]

bool xtd::io::file_info::is_read_only ( ) const

Gets a value that determines if the current file is read only.

Returns
true if the current file is read only; otherwise, false.
Exceptions
xtd::io::file_not_found_exceptionThe file described by the current xtd::io::file_info object could not be found.
xtd::io::io_exceptionAn I/O error occurred while opening the file.
xtd::unauthorized_access_exceptionThis operation is not supported on the current platform.
-or-
The caller does not have the required permission.
xtd::argument_exceptionThe user does not have write permission, but attempted to set this property to false.
Examples
The following example uses the xtd::io::file_info::is_read_only property to mark a file as read only and then mark it as read-write.
#include <xtd/xtd>
using namespace xtd;
using namespace xtd::io;
class program {
public:
static auto main() {
ustring file_name = R"(c:\test.xml)";
// Get the read-only value for a file.
bool is_read_only = is_file_read_only(file_name);
// Display wether the file is read-only.
console::write_line("The file read-only value for " + file_name + " is: " + is_read_only);
console::write_line("Changing the read-only value for " + file_name + " to true.");
// Set the file to read-only.
set_file_read_access(file_name, true);
// Get the read-only value for a file.
is_read_only = is_file_read_only(file_name);
// Display that the file is read-only.
console::write_line("The file read-only value for " + file_name + " is: " + is_read_only);
}
// Sets the read-only value of a file.
static void set_file_read_access(const ustring& file_name, bool set_read_only) {
// Create a new xtd::io::file_info object.
file_info f_info(file_name);
// Set the IsReadOnly property.
f_info.is_read_only(set_read_only);
}
// Returns wether a file is read-only.
static bool is_file_read_only(const ustring& file_name) {
// Create a new xtd::io::file_info object.
file_info f_info(file_name);
// Return the IsReadOnly property value.
return f_info.is_read_only();
}
};
startup_(program::main);
// This code produces output similar to the following;
// results may vary based on the computer/file structure/etc.:
//
// The file read-only value for c:\test.xml is: True
// Changing the read-only value for c:\test.xml to true.
// The file read-only value for c:\test.xml is: True
Remarks
Use the xtd::io::file_info::is_read_only property to quickly determine or change whether the current file is read only.
When first called, file_info calls xtd::io::file_info::refresh and caches information about the file. On subsequent calls, you must call xtd::io::file_info::refresh to get the latest copy of the information.

◆ is_read_only() [2/2]

void xtd::io::file_info::is_read_only ( bool  value)

Sets a value that determines if the current file is read only.

Parameters
valuetrue if the current file is read only; otherwise, false.
Exceptions
xtd::io::file_not_found_exceptionThe file described by the current xtd::io::file_info object could not be found.
xtd::io::io_exceptionAn I/O error occurred while opening the file.
xtd::unauthorized_access_exceptionThis operation is not supported on the current platform.
-or-
The caller does not have the required permission.
xtd::argument_exceptionThe user does not have write permission, but attempted to set this property to false.
Examples
The following example uses the xtd::io::file_info::is_read_only property to mark a file as read only and then mark it as read-write.
#include <xtd/xtd>
using namespace xtd;
using namespace xtd::io;
class program {
public:
static auto main() {
ustring file_name = R"(c:\test.xml)";
// Get the read-only value for a file.
bool is_read_only = is_file_read_only(file_name);
// Display wether the file is read-only.
console::write_line("The file read-only value for " + file_name + " is: " + is_read_only);
console::write_line("Changing the read-only value for " + file_name + " to true.");
// Set the file to read-only.
set_file_read_access(file_name, true);
// Get the read-only value for a file.
is_read_only = is_file_read_only(file_name);
// Display that the file is read-only.
console::write_line("The file read-only value for " + file_name + " is: " + is_read_only);
}
// Sets the read-only value of a file.
static void set_file_read_access(const ustring& file_name, bool set_read_only) {
// Create a new xtd::io::file_info object.
file_info f_info(file_name);
// Set the IsReadOnly property.
f_info.is_read_only(set_read_only);
}
// Returns wether a file is read-only.
static bool is_file_read_only(const ustring& file_name) {
// Create a new xtd::io::file_info object.
file_info f_info(file_name);
// Return the IsReadOnly property value.
return f_info.is_read_only();
}
};
startup_(program::main);
// This code produces output similar to the following;
// results may vary based on the computer/file structure/etc.:
//
// The file read-only value for c:\test.xml is: True
// Changing the read-only value for c:\test.xml to true.
// The file read-only value for c:\test.xml is: True
Remarks
Use the xtd::io::file_info::is_read_only property to quickly determine or change whether the current file is read only.
When first called, file_info calls xtd::io::file_info::refresh and caches information about the file. On subsequent calls, you must call xtd::io::file_info::refresh to get the latest copy of the information.

◆ length()

size_t xtd::io::file_info::length ( ) const

Gets the size, in bytes, of the current file.

Returns
The size of the current file in bytes.
Exceptions
xtd::io::io_exceptionxtd::io::file_info::refresh cannot update the state of the file or directory.
xtd::io::file_not_found_exceptionThe file does not exist.
-or-
The xtd::io::file_info::size property is called for a directory.
Examples
#include <xtd/xtd>
using namespace std;
using namespace xtd;
using namespace xtd::io;
auto main()->int {
// Make a reference to a directory.
directory_info di("c:\\");
// Get a reference to each file in that directory.
vector<file_info> fi_arr = di.get_files();
// Display the names and sizes of the files.
console::write_line("The directory {0} contains the following files:", di.name());
for (file_info f : fi_arr)
console::write_line("The size of {0} is {1} bytes.", f.name(), f.length());
}
// This code produces the following to the following;
// results may vary based on the computer/file structure/etc.:
//
// The directory c:\ contains the following files:
// The size of MyComputer.log is 274 bytes.
// The size of AUTOEXEC.BAT is 0 bytes.
// The size of boot.ini is 211 bytes.
// The size of CONFIG.SYS is 0 bytes.
// The size of hiberfil.sys is 1072775168 bytes.
// The size of IO.SYS is 0 bytes.
// The size of MASK.txt is 2700 bytes.
// The size of mfc80.dll is 1093632 bytes.
// The size of mfc80u.dll is 1079808 bytes.
// The size of MSDOS.SYS is 0 bytes.
// The size of NTDETECT.COM is 47564 bytes.
// The size of ntldr is 250032 bytes.
// The size of pagefile.sys is 1610612736 bytes.
// The size of UpdatePatch.log is 22778 bytes.
// The size of UpdatePatch.txt is 30 bytes.
// The size of wt3d.ini is 234 bytes.
Represents the standard input, output, and error streams for console applications.
Definition console.h:33
Exposes instance methods for creating, moving, and enumerating through directories and subdirectories...
Definition directory_info.h:127
xtd::ustring name() const override
Gets the name of the file.
size_t length() const
Gets the size, in bytes, of the current file.
@ f
The F key.
Remarks
The value of the Length property is pre-cached if the current instance of the xtd::io::file_info object was returned from any of the following DirectoryInfo methods:
  • xtd::io::file_info::get_directories
  • xtd::io::file_info::_det_files
  • xtd::io::file_info::get_file_system_infos
  • xtd::io::file_info::enumerate_directories
  • xtd::io::file_info::enumerate_files
  • xtd::io::file_info::enumerate_file_system_infos
  • To get the latest value, call the xtd::io::file_info::refresh method.
Examples
file_info2.cpp.

◆ move_to() [1/2]

void xtd::io::file_info::move_to ( const xtd::ustring dest_file_name)

Moves a specified file to a new location, providing the option to specify a new file name.

Parameters
dest_file_nameThe path to move the file to, which can specify a different file name.
Exceptions
xtd::io::io_exceptionAn I/O error occurs, such as the destination file already exists or the destination device is not ready.
xtd::argument_exceptiondest_file_name is empty, contains only white spaces, or contains invalid characters.
xtd::security::security_exceptionThe caller does not have the required permission.
xtd::unauthorized_access_exceptiondest_file_name is read-only or is a directory.
xtd::io::file_not_found_exceptionThe file is not found.
xtd::io::directory_not_found_exceptionThe specified path is invalid, such as being on an unmapped drive.
xtd::io::path_too_long_exceptionThe specified path, file name, or both exceed the system-defined maximum length.
xtd::not_supported_exceptiondest_file_name contains a colon (:) in the middle of the string.
Examples
The following example demonstrates moving a file to a different location and renaming the file.
#include <xtd/io/file_info>
#include <xtd/io/directory_info>
#include <xtd/io/path>
#include <xtd/console>
#include <xtd/environment>
#include <xtd/startup>
using namespace std;
using namespace xtd;
using namespace xtd::io;
class program {
private:
inline static ustring source_path = path::combine(environment::get_folder_path(environment::special_folder::my_documents), "file_info_test_directory", "move_from", "from_file.xml");
inline static ustring dest_path = path::combine(environment::get_folder_path(environment::special_folder::my_documents), "file_info_test_directory", "dest_filexml");
public:
//
// The main entry point for the application.
//
static auto main() {
// Change Console properties to make it obvious that
// the application is starting.
console::clear();
// Move it to the upper left corner of the screen.
console::set_window_position(0, 0);
// Make it very large.
console::set_window_size(console::largest_window_width() - 24, console::largest_window_height() - 16);
console::write_line("Welcome.");
console::write_line("This application demonstrates the file_info::move_to method.");
console::write_line("Press any key to start.");
console::read_key();
console::write(" Checking whether ");
console::write(source_path);
console::write_line(" exists.");
auto f_info = file_info {source_path};
ensure_source_file_exists();
display_file_properties(f_info);
console::write_line("Preparing to move the file to ");
console::write(dest_path);
console::write_line(".");
move_file(f_info);
display_file_properties(f_info);
console::write_line("Preparing to delete directories.");
delete_files();
console::write_line("Press the ENTER key to close this application.");
console::read_key();
}
private:
//
// Moves the supplied file_info instance to dest_path.
//
static void move_file(file_info& f_info) {
try {
f_info.move_to(dest_path);
console::write_line("File moved to ");
console::write_line(dest_path);
} catch (const system_exception& ex) {
display_exception(ex);
}
}
//
// Ensures that the test directories
// and the file FromFile.xml all exist.
//
static void ensure_source_file_exists() {
auto f_info = file_info {source_path};
auto dir_path = f_info.directory().full_name();
if (!directory::exists(dir_path))
directory::create_directory(dir_path);
if (file::exists(dest_path))
file::remove(dest_path);
console::write("Creating file ");
console::write(f_info.full_name());
console::write_line(".");
try {
if (!f_info.exists()) {
console::write_line("Adding data to the file.");
write_file_content(10);
console::write_line("Successfully created the file.");
}
} catch (const system_exception& ex) {
display_exception(ex);
}
}
//
// Creates and saves an Xml file to source_path.
//
static void write_file_content(int total_element) {
auto lines = vector<ustring> {};
lines.push_back("<?xml version=\"1.0\" standalone=\"yes\"?>");
for (auto index = 0; index < total_element; ++index)
lines.push_back(ustring::format("<MyElement Index=\"{0}\">\nMyElement at position {0}.", index));
file::write_all_lines(source_path, lines);
}
//
// Displays FullName, CreationTime, and LastWriteTime of the supplied
// file_info instance, then displays the text of the file.
//
static void display_file_properties(const file_info& f_info) {
console::write_line("The file_info instance shows these property values.");
try {
console::write("Full_name: ");
console::write_line(f_info.full_name());
console::write("creation_time: ");
console::write_line(f_info.creation_time());
console::write("last_write_time: ");
console::write_line(f_info.last_write_time());
console::write_line();
console::write_line("file contents:");
console::write_line();
stream_reader reader(f_info.full_name());
while (!reader.end_of_stream())
console::write_line(reader.read_line());
console::write_line();
} catch (const system_exception& ex) {
display_exception(ex);
}
}
//
// Deletes the test directory and all its files and subdirectories.
//
static void delete_files() {
try {
auto d_info = directory_info {path::combine(environment::get_folder_path(environment::special_folder::my_documents), "file_infoTestDirectory")};
if (d_info.exists()) {
d_info.remove(true);
console::write_line("Successfully deleted directories and files.");
}
} catch (const system_exception& ex) {
display_exception(ex);
}
}
//
// Displays information about the supplied Exception. This
// code is not suitable for production applications.
//
static void display_exception(const system_exception& ex) {
auto s = ustring::empty_string;
s += "An exception of type \"";
s += typeof_(ex).full_name();
s += "\" has occurred.\r\n";
s += ex.message();
s += "\r\nStack trace information:\r\n";
s += ex.stack_trace();
console::write_line(s);
}
};
startup_(program::main);
// This code produces the following output :
// results may vary based on the computer/file structure/etc.:
//
// Welcome.
// This application demonstrates the file_info.move_to method.
// Press any key to start.
//
// Checking whether C:\Documents and Settings\MyComputer\My Documents\file_infoTestDirectory\MoveFrom\FromFile.xml exists.
// Creating file C:\Documents and Settings\MyComputer\My Documents\file_infoTestDirectory\MoveFrom\FromFile.xml.
// Adding data to the file.
// Successfully created the file.
// The file_info instance shows these property values.
// FullName: C:\Documents and Settings\MyComputer\My Documents\file_infoTestDirectory\MoveFrom\FromFile.xml
// CreationTime: 4/18/2006 1:24:19 PM
// LastWriteTime: 4/18/2006 1:24:19 PM
//
// File contents:
//
// <?xml version="1.0" standalone="yes"?>
// <MyElement Index="0">
// MyElement at position 0.
// <MyElement Index="1">
// MyElement at position 1.
// <MyElement Index="2">
// MyElement at position 2.
// <MyElement Index="3">
// MyElement at position 3.
// <MyElement Index="4">
// MyElement at position 4.
// <MyElement Index="5">
// MyElement at position 5.
// <MyElement Index="6">
// MyElement at position 6.
// <MyElement Index="7">
// MyElement at position 7.
// <MyElement Index="8">
// MyElement at position 8.
// <MyElement Index="9">
// MyElement at position 9.
// Preparing to move the file to
// C:\Documents and Settings\MYComputer\My Documents\file_infoTestDirectory\DestFile.xml.
// File moved to
// C:\Documents and Settings\MYComputer\My Documents\file_infoTestDirectory\DestFile.xml
// The file_info instance shows these property values.
// FullName: C:\Documents and Settings\MYComputer\My Documents\file_infoTestDirectory\DestFile.xml
// CreationTime: 4/18/2006 1:24:19 PM
// LastWriteTime: 4/18/2006 1:24:19 PM
//
// File contents:
//
// <?xml version="1.0" standalone="yes"?>
// <MyElement Index="0">
// MyElement at position 0.
// <MyElement Index="1">
// MyElement at position 1.
// <MyElement Index="2">
// MyElement at position 2.
// <MyElement Index="3">
// MyElement at position 3.
// <MyElement Index="4">
// MyElement at position 4.
// <MyElement Index="5">
// MyElement at position 5.
// <MyElement Index="6">
// MyElement at position 6.
// <MyElement Index="7">
// MyElement at position 7.
// <MyElement Index="8">
// MyElement at position 8.
// <MyElement Index="9">
// MyElement at position 9.
//
// Preparing to delete directories.
// Successfully deleted directories and files.
// Press the ENTER key to close this application.
void remove() const override
Deletes this xtd::io::directory_info if it is empty.
void move_to(const xtd::ustring &dest_file_name)
Moves a specified file to a new location, providing the option to specify a new file name.
xtd::io::directory_info directory() const
Gets an instance of the parent directory.
xtd::ustring full_name() const
Gets the full path of the directory or file.
const xtd::date_time & creation_time() const
Gets the creation time of the current file or directory.
const xtd::date_time & last_write_time() const
Gets the time when the current file or directory was last written to.
virtual xtd::ustring stack_trace() const noexcept
Gets a string representation of the immediate frames on the call stack.
#define typeof_
Used to obtain the type object of a specified type or object.
Definition typeof.h:45
Remarks
This method works across disk volumes. For example, the file c:\MyFile.txt can be moved to d:and renamed NewFile.txt.
This method does not overwrite the destination file if it already exists. For that purpose, call xtd::ioo::file_info::move_to(ustring, bool) instead.
Examples
file_info_move_to.cpp.

◆ move_to() [2/2]

void xtd::io::file_info::move_to ( const xtd::ustring dest_file_name,
bool  overwrite 
)

Moves a specified file to a new location, providing the options to specify a new file name and to overwrite the destination file if it already exists.

Parameters
dest_file_nameThe path to move the file to, which can specify a different file name.
overwritetrue to overwrite the destination file if it already exists; false otherwise.
Exceptions
xtd::io::io_exceptionAn I/O error occurred, such as the destination device is not ready.
xtd::argument_exceptiondest_file_name is empty, contains only white spaces, or contains invalid characters.
xtd::security::security_exceptionThe caller does not have the required permission.
xtd::unauthorized_access_exceptiondest_file_name is read-only or is a directory.
xtd::io::file_not_found_exceptionThe file is not found.
xtd::io::directory_not_found_exceptionThe specified path is invalid, such as being on an unmapped drive.
xtd::io::path_too_long_exceptionThe specified path, file name, or both exceed the system-defined maximum length.
xtd::not_supported_exceptiondest_file_name contains a colon (:) in the middle of the string.
Examples
The following example demonstrates moving a file to a different location and renaming the file.
#include <xtd/io/file_info>
#include <xtd/io/directory_info>
#include <xtd/io/path>
#include <xtd/console>
#include <xtd/environment>
#include <xtd/startup>
using namespace std;
using namespace xtd;
using namespace xtd::io;
class program {
private:
inline static ustring source_path = path::combine(environment::get_folder_path(environment::special_folder::my_documents), "file_info_test_directory", "move_from", "from_file.xml");
inline static ustring dest_path = path::combine(environment::get_folder_path(environment::special_folder::my_documents), "file_info_test_directory", "dest_filexml");
public:
//
// The main entry point for the application.
//
static auto main() {
// Change Console properties to make it obvious that
// the application is starting.
console::clear();
// Move it to the upper left corner of the screen.
console::set_window_position(0, 0);
// Make it very large.
console::set_window_size(console::largest_window_width() - 24, console::largest_window_height() - 16);
console::write_line("Welcome.");
console::write_line("This application demonstrates the file_info::move_to method.");
console::write_line("Press any key to start.");
console::read_key();
console::write(" Checking whether ");
console::write(source_path);
console::write_line(" exists.");
auto f_info = file_info {source_path};
ensure_source_file_exists();
display_file_properties(f_info);
console::write_line("Preparing to move the file to ");
console::write(dest_path);
console::write_line(".");
move_file(f_info);
display_file_properties(f_info);
console::write_line("Preparing to delete directories.");
delete_files();
console::write_line("Press the ENTER key to close this application.");
console::read_key();
}
private:
//
// Moves the supplied file_info instance to dest_path.
//
static void move_file(file_info& f_info) {
try {
f_info.move_to(dest_path);
console::write_line("File moved to ");
console::write_line(dest_path);
} catch (const system_exception& ex) {
display_exception(ex);
}
}
//
// Ensures that the test directories
// and the file FromFile.xml all exist.
//
static void ensure_source_file_exists() {
auto f_info = file_info {source_path};
auto dir_path = f_info.directory().full_name();
if (!directory::exists(dir_path))
directory::create_directory(dir_path);
if (file::exists(dest_path))
file::remove(dest_path);
console::write("Creating file ");
console::write(f_info.full_name());
console::write_line(".");
try {
if (!f_info.exists()) {
console::write_line("Adding data to the file.");
write_file_content(10);
console::write_line("Successfully created the file.");
}
} catch (const system_exception& ex) {
display_exception(ex);
}
}
//
// Creates and saves an Xml file to source_path.
//
static void write_file_content(int total_element) {
auto lines = vector<ustring> {};
lines.push_back("<?xml version=\"1.0\" standalone=\"yes\"?>");
for (auto index = 0; index < total_element; ++index)
lines.push_back(ustring::format("<MyElement Index=\"{0}\">\nMyElement at position {0}.", index));
file::write_all_lines(source_path, lines);
}
//
// Displays FullName, CreationTime, and LastWriteTime of the supplied
// file_info instance, then displays the text of the file.
//
static void display_file_properties(const file_info& f_info) {
console::write_line("The file_info instance shows these property values.");
try {
console::write("Full_name: ");
console::write_line(f_info.full_name());
console::write("creation_time: ");
console::write_line(f_info.creation_time());
console::write("last_write_time: ");
console::write_line(f_info.last_write_time());
console::write_line();
console::write_line("file contents:");
console::write_line();
stream_reader reader(f_info.full_name());
while (!reader.end_of_stream())
console::write_line(reader.read_line());
console::write_line();
} catch (const system_exception& ex) {
display_exception(ex);
}
}
//
// Deletes the test directory and all its files and subdirectories.
//
static void delete_files() {
try {
auto d_info = directory_info {path::combine(environment::get_folder_path(environment::special_folder::my_documents), "file_infoTestDirectory")};
if (d_info.exists()) {
d_info.remove(true);
console::write_line("Successfully deleted directories and files.");
}
} catch (const system_exception& ex) {
display_exception(ex);
}
}
//
// Displays information about the supplied Exception. This
// code is not suitable for production applications.
//
static void display_exception(const system_exception& ex) {
auto s = ustring::empty_string;
s += "An exception of type \"";
s += typeof_(ex).full_name();
s += "\" has occurred.\r\n";
s += ex.message();
s += "\r\nStack trace information:\r\n";
s += ex.stack_trace();
console::write_line(s);
}
};
startup_(program::main);
// This code produces the following output :
// results may vary based on the computer/file structure/etc.:
//
// Welcome.
// This application demonstrates the file_info.move_to method.
// Press any key to start.
//
// Checking whether C:\Documents and Settings\MyComputer\My Documents\file_infoTestDirectory\MoveFrom\FromFile.xml exists.
// Creating file C:\Documents and Settings\MyComputer\My Documents\file_infoTestDirectory\MoveFrom\FromFile.xml.
// Adding data to the file.
// Successfully created the file.
// The file_info instance shows these property values.
// FullName: C:\Documents and Settings\MyComputer\My Documents\file_infoTestDirectory\MoveFrom\FromFile.xml
// CreationTime: 4/18/2006 1:24:19 PM
// LastWriteTime: 4/18/2006 1:24:19 PM
//
// File contents:
//
// <?xml version="1.0" standalone="yes"?>
// <MyElement Index="0">
// MyElement at position 0.
// <MyElement Index="1">
// MyElement at position 1.
// <MyElement Index="2">
// MyElement at position 2.
// <MyElement Index="3">
// MyElement at position 3.
// <MyElement Index="4">
// MyElement at position 4.
// <MyElement Index="5">
// MyElement at position 5.
// <MyElement Index="6">
// MyElement at position 6.
// <MyElement Index="7">
// MyElement at position 7.
// <MyElement Index="8">
// MyElement at position 8.
// <MyElement Index="9">
// MyElement at position 9.
// Preparing to move the file to
// C:\Documents and Settings\MYComputer\My Documents\file_infoTestDirectory\DestFile.xml.
// File moved to
// C:\Documents and Settings\MYComputer\My Documents\file_infoTestDirectory\DestFile.xml
// The file_info instance shows these property values.
// FullName: C:\Documents and Settings\MYComputer\My Documents\file_infoTestDirectory\DestFile.xml
// CreationTime: 4/18/2006 1:24:19 PM
// LastWriteTime: 4/18/2006 1:24:19 PM
//
// File contents:
//
// <?xml version="1.0" standalone="yes"?>
// <MyElement Index="0">
// MyElement at position 0.
// <MyElement Index="1">
// MyElement at position 1.
// <MyElement Index="2">
// MyElement at position 2.
// <MyElement Index="3">
// MyElement at position 3.
// <MyElement Index="4">
// MyElement at position 4.
// <MyElement Index="5">
// MyElement at position 5.
// <MyElement Index="6">
// MyElement at position 6.
// <MyElement Index="7">
// MyElement at position 7.
// <MyElement Index="8">
// MyElement at position 8.
// <MyElement Index="9">
// MyElement at position 9.
//
// Preparing to delete directories.
// Successfully deleted directories and files.
// Press the ENTER key to close this application.
Remarks
This method works across disk volumes. For example, the file c:\MyFile.txt can be moved to d:and renamed NewFile.txt.

◆ name()

xtd::ustring xtd::io::file_info::name ( ) const
overridevirtual

Gets the name of the file.

Returns
The name of the file.
Examples
#include <xtd/xtd>
using namespace std;
using namespace xtd;
using namespace xtd::io;
auto main()->int {
// Create a reference to the current directory.
// Create an array representing the files in the current directory.
vector<file_info> fi = di.get_files();
console::write_line("The following files exist in the current directory:");
// Print out the names of the files in the current directory.
for (file_info fi_temp : fi)
console::write_line(fi_temp.name());
}
// This code produces output similar to the following;
// results may vary based on the computer/file structure/etc.:
//
// The following files exist in the current directory:
// fileinfoname.exe
// fileinfoname.pdb
// newTemp.txt
static xtd::ustring current_directory()
Gets the fully qualified path of the current working directory.
Remarks
When first called, xtd::io::file_info calls Refresh and caches information about the file. On subsequent calls, you must call Refresh to get the latest copy of the information.
The name of the file includes the file extension.

Implements xtd::io::file_system_info.

Examples
file_info2.cpp.

◆ open()

std::fstream xtd::io::file_info::open ( std::ios::openmode  mode) const

Opens a file in the specified mode.

Parameters
modeA std::ios::openmode constant specifying the mode (for example, std::ios::openmode::in or std::ios::openmode::app) in which to open the file.
Returns
A file opened in the specified mode, with read/write access and unshared.
Exceptions
xtd::io::file_not_found_exceptionThe file is not found.
xtd::unauthorized_access_exceptionThe file is read-only or is a directory.
xtd::io::directory_not_found_exceptionThe specified path is invalid, such as being on an unmapped drive.
xtd::io::io_exceptionThe file is already open.
Examples
The following example opens a file, adds some information to the file, and reads the file.
#include <xtd/io/file_info>
#include <xtd/io/stream_reader>
#include <xtd/io/stream_writer>
#include <xtd/console>
#include <xtd/startup>
#include <xtd/using>
using namespace std;
using namespace xtd;
using namespace xtd::io;
class program {
public:
static auto main() {
auto path = "MyTest.txt";
auto fi = file_info {path};
// Delete the file if it exists.
if (fi.exists())
fi.remove();
//Create the file.
using_(auto fs = fi.create()) {
auto sw = stream_writer {fs};
sw.write_line("This is some text in the file.");
}
//Open the stream and read it back.
using_(auto fs = fi.open(ios::in)) {
auto sr = stream_reader {fs};
while (!sr.end_of_stream())
console::write_line(sr.read_line());
}
}
};
startup_(program::main);
// This code produces the following output :
//
// This is some text in the file.

◆ open_read()

std::ifstream xtd::io::file_info::open_read ( ) const

Creates a read-only std::ifstream.

Returns
A new read-only std::ifstream.
Exceptions
xtd::unauthorized_access_exceptionname is read-only or is a directory.
xtd::io::directory_not_found_exceptionThe specified path is invalid, such as being on an unmapped drive.
xtd::io::io_exceptionThe file is already open.
Examples
The following example opens a file as read-only and reads from it.
#include <xtd/io/file_info>
#include <xtd/io/stream_reader>
#include <xtd/io/stream_writer>
#include <xtd/console>
#include <xtd/startup>
#include <xtd/using>
using namespace xtd;
using namespace xtd::io;
class program {
public:
static auto main() {
auto path = "MyTest.txt";
auto fi = file_info {path};
//Create the file.
using_(auto fs = fi.create()) {
auto sw = stream_writer {fs};
sw.write_line("This is some text in the file.");
}
//Open the stream and read it back.
using_(auto fs = fi.open_read()) {
auto sr = stream_reader {fs};
while (!sr.end_of_stream())
console::write_line(sr.read_line());
}
}
};
startup_(program::main);
// This code produces the following output :
// results may vary based on the computer/file structure/etc.:
//
// This is some text in the file.
Remarks
This method returns a read-only std::ifstream object.

◆ open_text()

xtd::io::stream_reader xtd::io::file_info::open_text ( ) const

Creates a xtd::io::stream_reader that reads from an existing text file.

Returns
A new xtd::io::stream_reader.
Exceptions
xtd::security::security_exceptionThe caller does not have the required permission.
xtd::io::file_not_found_exceptionThe file is not found.
xtd::unauthorized_access_exceptionname is read-only or is a directory.
xtd::io::directory_not_found_exceptionThe specified path is invalid, such as being on an unmapped drive.
Examples
The following example demonstrates the xtd::io::file_info::create_text method.
#include <xtd/io/file_info>
#include <xtd/io/path>
#include <xtd/console>
#include <xtd/startup>
#include <xtd/using>
using namespace xtd;
using namespace xtd::io;
class program {
public:
static auto main() {
auto path = path::combine(path::get_temp_path(), "MyTest.txt");
auto fi = file_info {path};
if (!fi.exists()) {
//Create a file to write to.
using_(auto sw = fi.create_text()) {
sw.write_line("Hello");
sw.write_line("And");
sw.write_line("Welcome");
}
}
//Open the file to read from.
using_(auto sr = fi.open_text()) {
while (!sr.end_of_stream())
console::write_line(sr.read_line());
}
}
};
startup_(program::main);
// This code produces output similar to the following;
// results may vary based on the computer/file structure/etc.:
//
// Hello
// And
// Welcome
Examples
file_info.cpp.

◆ open_write()

std::ofstream xtd::io::file_info::open_write ( ) const

Creates a write-only std::ofstream.

Returns
A write-only unshared std::ofstream object for a new or existing file.
Exceptions
xtd::unauthorized_access_exceptionThe path specified when creating an instance of the xtd::io::file_info object is read-only or is a directory.
xtd::io::directory_not_found_exceptionThe path specified when creating an instance of the xtd::io::file_info object is invalid, such as being on an unmapped drive.
Examples
The following example opens a file for writing and then reads from the file.
#include <xtd/io/file_info>
#include <xtd/io/stream_reader>
#include <xtd/io/stream_writer>
#include <xtd/console>
#include <xtd/startup>
#include <xtd/using>
using namespace std;
using namespace xtd;
using namespace xtd::io;
class program {
public:
static auto main() {
auto path = "MyTest.txt";
auto fi = file_info {path};
// Delete the file if it exists.
if (fi.exists())
fi.remove();
//Create the file.
using_(auto fs = fi.create()) {
auto sw = stream_writer {fs};
sw.write_line("This is some text in the file.");
}
//Open the stream and read it back.
using_(auto fs = fi.open(ios::in)) {
auto sr = stream_reader {fs};
while (!sr.end_of_stream())
console::write_line(sr.read_line());
}
}
};
startup_(program::main);
// This code produces the following output :
//
// This is some text in the file.
Returns
The xtd::io::file_info::open_write method opens a file if one already exists for the file path, or creates a new file if one does not exist. For an existing file, it does not append the new text to the existing text. Instead, it overwrites the existing characters with the new characters. If you overwrite a longer string (such as "This is a test of the open_write method") with a shorter string (like "Second run"), the file will contain a mix of the strings ("Second runtest of the open_write method").

◆ remove()

void xtd::io::file_info::remove ( ) const
overridevirtual

Permanently deletes a file.

Exceptions
xtd::io::io_exceptionThe target file is open or memory-mapped on a computer running Microsoft Windows NT.
-or-
There is an open handle on the file, and the operating system is Windows XP or earlier. This open handle can result from enumerating directories and files. For more information, see How to: Enumerate Directories and Files.
xtd::security::security_exceptionThe caller does not have the required permission.
xtd::unauthorized_access_exceptionThe path is a directory.
Examples
The following example demonstrates the xtd::io::file_info::remove method.
#include <xtd/xtd>
using namespace std;
using namespace xtd;
using namespace xtd::io;
class program {
public:
static auto main() {
ustring path = R"(c:\MyTest.txt)";
try {
using_ (ofstream ofs = fi1.create_text()) {}
ustring path2 = path + "temp";
file_info fi2(path2);
//Ensure that the target does not exist.
fi2.remove();
//Copy the file.
fi1.copy_to(path2);
console::write_line("{0} was copied to {1}.", path, path2);
//Delete the newly created file.
fi2.remove();
console::write_line("{0} was successfully deleted.", path2);
} catch (const system_exception& e) {
console::write_line("The process failed: {0}", e.to_string());
}
}
};
startup_(program::main);
// This code produces output similar to the following;
// results may vary based on the computer/file structure/etc.:
//
//c:\MyTest.txt was copied to c:\MyTest.txttemp.
//c:\MyTest.txttemp was successfully deleted.
Examples
The following example creates, closes, and deletes a file.
#include <xtd/xtd>
using namespace std;
using namespace xtd::io;
class program {
public:
static auto main() {
// Create a reference to a file.
file_info fi("temp.txt");
// Actually create the file.
ofstream ofs = fi.create();
// Modify the file as required, and then close the file.
ofs.close();
// Delete the file.
fi.remove();
}
};
startup_(program::main);
Remarks
If the file does not exist, this method does nothing.

Implements xtd::io::file_system_info.

Examples
file_info.cpp.

◆ replace()

file_info xtd::io::file_info::replace ( const xtd::ustring destination_file_name,
const xtd::ustring destination_backup_file_name 
)

Replaces the contents of a specified file with the file described by the current xtd::io::file_info object, deleting the original file, and creating a backup of the replaced file.

Parameters
destination_file_nameThe name of a file to replace with the current file.
destination_backup_file_nameThe name of a file with which to create a backup of the file described by the destFileName parameter.
Returns
A xtd::io::file_info object that encapsulates information about the file described by the destFileName parameter.
Exceptions
xtd::argument_exceptionThe path described by the destFileName parameter was not of a legal form.
-or-
The path described by the destBackupFileName parameter was not of a legal form.
xtd::io::file_not_found_exceptionThe file described by the current xtd::io::file_info object could not be found.
-or-
The file described by the destinationFileName parameter could not be found.
xtd::platform_not_supported_exceptionThe current operating system is not Microsoft Windows NT or later.
Examples
The following example uses the xtd::io::file_info::replace method to replace a file with another file and create a backup of the replaced file.
#include <xtd/io/file>
#include <xtd/io/file_info>
#include <xtd/console>
#include <xtd/startup>
using namespace xtd;
using namespace xtd::io;
class program {
public:
static auto main() {
try {
// original_file and file_to_replace must contain the path to files that already exist in the
// file system. backup_of_file_to_replace is created during the execution of the Replace method.
auto original_file = "test.txt"_s;
auto file_to_replace = "test2.txt"_s;
auto backup_of_file_to_replace = "test2.txt.bak"_s;
if (file::exists(original_file) && file::exists(file_to_replace)) {
console::write_line("Move the contents of " + original_file + " into " + file_to_replace + ", delete " + original_file + ", and create a backup of " + file_to_replace + ".");
// Replace the file.
replace_file(original_file, file_to_replace, backup_of_file_to_replace);
console::write_line("Done");
} else
console::write_line("Either the file {0} or {1} doesn't exist.", original_file, file_to_replace);
} catch (const system_exception& e) {
console::write_line(e.message());
}
console::read_key();
}
// Move a file into another file, delete the original, and create a backup of the replaced file.
static void replace_file(const ustring& file_to_move_and_delete, const ustring& file_to_replace, const ustring& backup_of_file_to_replace) {
// Create a new file_info object.
auto f_info = file_info {file_to_move_and_delete};
// replace the file.
f_info.replace(file_to_replace, backup_of_file_to_replace);
}
};
startup_(program::main);
// This code produces the following output :
//
// Move the contents of test.txt into test2.txt, delete test.txt, and create a backup of test2.txt.
// Done
ustring replace(value_type old_char, value_type new_char) const noexcept
Replaces all occurrences of a specified char_t in this string with another specified char_t.
Remarks
The Replace method replaces the contents of a specified file with the contents of the file described by the current xtd::io::file_info object. It also creates a backup of the file that was replaced. Finally, it returns a new xtd::io::file_info object that describes the overwritten file.
Pass an empty string ("") to the dest_backup_file_name parameter if you do not want to create a backup of the file being replaced.

Member Data Documentation

◆ empty

const file_info xtd::io::file_info::empty
static

Represents the uninitialized xtd::io::file_info object. This field is constant.


The documentation for this class was generated from the following file: