如何在应用程序中创建文件?

问题描述:

我想创建一个logFile和一个目录/文件,用于存储我的应用程序已在我的应用程序目录中序列化的对象.我该怎么办?我知道如何创建目录和文件,但是我想在我的应用程序父目录中创建一个子目录.例子:我一直在做测试的目的是创建一个目录. string dir ="C:\ MyDir \ ..."; Directory.Create(dir)...,我将任何与我的应用程序相关的信息存储在此目录中,但是我想创建一个内部"目录来存储我所有与应用程序相关的信息,而不是创建外部目录在用户的硬盘驱动器上...

I want to create a logFile and a directory/file that stores objects that my application has serialized within my application''s directory. How do I go about this? I know how to create directories and files but I want to create a subDirectory within my applications parent directory. Example: what I''ve been doing for testing purposes is I''ll create a directory; string dir = "C:\MyDir\..."; Directory.Create(dir)... and I store whatever info in this directory that''s relevant to my app, but I want to create a "internal" directory to store all of my apps relevant info and not create a external directory on the user''s hardDrive...

IsolatedStorage是解决您问题的方法.

使用隔离存储,数据始终由用户和程序集隔离.凭据(例如程序集的来源或强名称)确定程序集的身份.数据也可以使用类似的凭据通过应用程序域隔离.

这是将内容存储在IsolatedStorage文件中的示例代码.

IsolatedStorage is the solution for your question.

With isolated storage, data is always isolated by user and by assembly. Credentials such as the origin or the strong name of the assembly determine assembly identity. Data can also be isolated by application domain, using similar credentials.

Here is the sample code to store the content in an IsolatedStorage file.

using System.IO;
using System.IO.IsolatedStorage;

const string ISOLATED_FILE_NAME = "MyIsolatedFile.txt";
IsolatedStorageFile isoStore = 
  IsolatedStorageFile.GetStore( IsolatedStorageScope.User 
  | IsolatedStorageScope.Assembly, null, null );

IsolatedStorageFileStream oStream = 
  new IsolatedStorageFileStream( ISOLATED_FILE_NAME, 
  FileMode.Create, isoStore );

StreamWriter writer = new StreamWriter( oStream );
writer.WriteLine( "This is my first line in the isolated storage file." );
writer.WriteLine( "This is second line." );
writer.Close();


string MyFileName = "MyFile.txt";
string MyLogPathName = "MyLog";
//application BasePath ex:D:\MyApp
string MyAppPath = System.AppDomain.CurrentDomain.BaseDirectory;

// D:\MyApp\MyLog
string MyLogPath = System.IO.Path.Combine(MyAppPath, MyLogPathName);

// D:\MyApp\MyFile.txt
string RelFilePath = System.IO.Path.Combine(MyAppPath, MyFileName);

// D:\MyApp\MyLog\MyFile.txt
string logFilePath = System.IO.Path.Combine(MyLogPath, MyFileName);


这并不大问题.您应该在依赖于路径的任何地方编写代码,以创建目录!
请注意,如果要在服务器上创建Dir,则需要有效的权限,例如在服务器上的读/写/执行.
Its a not a big issue. You should code for create directory on anywhere it depends on your path, which you want!
Note that if you want to create Dir on server then you need valid permission like read/write/execute on the server.