在运行时在c#中在所需路径上创建txt文件

时间:2013-06-21 11:46:15

标签: c# asp.net visual-studio-2008

我是C#的新手。我有一个问题,我想在运行时创建名为file的IP地址并将数据写入这些文件。我正在使用此代码,但它不起作用。它让我超越:

First chance exception of type 'System.NotSupportedException' occurred in mscorlib.dll

例外是:

System.NotSupportedException: The given path's format is not supported.

这是我的代码:

System.Diagnostics.Debug.Write( content);
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReadCallback), state);
System.Diagnostics.Debug.WriteLine(
    "Read {0} bytes from socket. \n Data : {1}", content);


string dir = @"C:\AppRecord";
if (!Directory.Exists(dir))
{
    Directory.CreateDirectory(dir);
}

File.WriteAllText(Path.Combine(dir,
     "log"+handler.RemoteEndPoint.ToString()+".txt"), content);

这是堆栈跟踪:

   A first chance exception of type 'System.NotSupportedException' occurred in mscorlib.dll
   at System.Security.Util.StringExpressionSet.CanonicalizePath(String path, Boolean needFullPath)
   at System.Security.Util.StringExpressionSet.CreateListFromExpressions(String[] str, Boolean needFullPath)
   at System.Security.Permissions.FileIOPermission.AddPathList(FileIOPermissionAccess access, AccessControlActions control, String[] pathListOrig, Boolean checkForDuplicates, Boolean needFullPath, Boolean copyPathList)
   at System.Security.Permissions.FileIOPermission..ctor(FileIOPermissionAccess access, AccessControlActions control, String[] pathList, Boolean checkForDuplicates, Boolean needFullPath)
   at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy)
   at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options)
   at System.IO.StreamWriter.CreateFile(String path, Boolean append)
   at System.IO.StreamWriter..ctor(String path, Boolean append, Encoding encoding, Int32 bufferSize)
   at System.IO.StreamWriter..ctor(String path, Boolean append, Encoding encoding)
   at System.IO.File.WriteAllText(String path, String contents, Encoding encoding)
   at System.IO.File.WriteAllText(String path, String contents)
   at ServerWService.Service1.AsynchronousSocketListener.ReadCallback(IAsyncResult ar)

1 个答案:

答案 0 :(得分:2)

我认为handler.RemoteEndPoint将返回一个IP地址,其端口由:分隔。但是,Windows上的文件名中不能包含字符:。您将不得不替换其他字符,例如下划线。