[英]changing a received file location in c# socket
我在 c# 中创建了一个 TCP 服务器,它从客户端接收一个文件并将其保存在当前目录中。 执行此操作的代码段如下:
using (FileStream fStream = new FileStream(Path.GetFileName(cmdFileName), FileMode.Create))
{
fStream.Write(buffer, 0, buffer.Length);
fStream.Flush();
fStream.Close();
}
Console.WriteLine("File received and saved in " + Environment.CurrentDirectory);
其中 cmdFileName 是接收到的文件名。
现在我使用以下代码在当前目录中创建了一个名为“test”的文件夹:
string root = Environment.CurrentDirectory;
string folder = Path.Combine(root,"test");
if (!Directory.Exists(folder)) Directory.CreateDirectory(folder);
我想将收到的文件保存在“test”文件夹中。 我需要对我之前的代码段的以下行进行更改:
using (FileStream fStream = new FileStream(Path.GetFileName(cmdFileName), FileMode.Create))
但是我必须做出什么改变?
您正在使用Path.Combine
来获取新test
目录的路径——您只需要再次使用它来查找test
目录中cmdFileName
文件的路径:
string cmdFilePath = Path.Combine(folder, Path.GetFileName(cmdFileName));
using (FileStream fStream = new FileStream(cmdFilePath, FileMode.Create))
在此代码之后:
string root = Environment.CurrentDirectory;
string folder = Path.Combine(root,"test");
if (!Directory.Exists(folder)) Directory.CreateDirectory(folder);
添加Path.Combine
另一种用法,因为您要将路径folder
附加到文件cmdFileName
:
string fullFilePath = Path.Combine(folder, Path.GetFileName(cmdFileName));
using (FileStream fStream = new FileStream(fullFilePath, FileMode.Create))
{
...
}
Console.WriteLine("File received and saved in " + fullFilePath);
此外,您应该希望在try
块中执行此操作,以便仅在确实成功时才宣布它成功:
try
{
using (FileStream fStream = new FileStream(fullFilePath, FileMode.Create)) //Exception accessing the file will prevent the console writing.
{
...
}
Console.WriteLine("File received and saved in " + fullFilePath);
}
catch (...){...Console.WriteLine("Could not write to file " + fullFilePath);...}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.