我在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))
但我必须做出哪些改变?
答案 0 :(得分:1)
您正在使用Path.Combine
获取新test
目录的路径 - 您只需再次使用它来查找{{1}内cmdFileName
文件的路径目录:
test
答案 1 :(得分:0)
在此代码之后:
void setup() {
// initialize digital pin 13 as an output.
pinMode(13, OUTPUT);
}
// the loop function runs over and over again forever
void loop() {
digitalWrite(13, HIGH); // turn the LED on (HIGH is the voltage level)
delay(1000); // wait for a second
digitalWrite(13, LOW); // turn the LED off by making the voltage LOW
delay(1000); // wait for a second
}
添加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