简体   繁体   English

在 C# 套接字中更改接收到的文件位置

[英]changing a received file location in c# socket

I have created a TCP server in c# which receives a file from a client and keeps it in the current directory.我在 c# 中创建了一个 TCP 服务器,它从客户端接收一个文件并将其保存在当前目录中。 The code segment which does this is as follows:执行此操作的代码段如下:

       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);

where cmdFileName is the received filename.其中 cmdFileName 是接收到的文件名。

Now I have created a folder named "test" inside the current directory using the following code:现在我使用以下代码在当前目录中创建了一个名为“test”的文件夹:

            string root = Environment.CurrentDirectory;
            string folder = Path.Combine(root,"test");
            if (!Directory.Exists(folder)) Directory.CreateDirectory(folder);

I want to keep the received file inside the "test" folder.我想将收到的文件保存在“test”文件夹中。 I need to make change to the following line of my previous code segment:我需要对我之前的代码段的以下行进行更改:

using (FileStream fStream = new FileStream(Path.GetFileName(cmdFileName), FileMode.Create))

But what change will I have to make?但是我必须做出什么改变?

You are using Path.Combine to get the path of the new test directory--you just need to use it again to find the path of the cmdFileName file inside the test directory:您正在使用Path.Combine来获取新test目录的路径——您只需要再次使用它来查找test目录中cmdFileName文件的路径:

string cmdFilePath = Path.Combine(folder, Path.GetFileName(cmdFileName));
using (FileStream fStream = new FileStream(cmdFilePath, FileMode.Create))

After this code:在此代码之后:

string root = Environment.CurrentDirectory;
string folder = Path.Combine(root,"test");
if (!Directory.Exists(folder)) Directory.CreateDirectory(folder);

Add another usage of the Path.Combine since you want to attach the path folder to the file cmdFileName :添加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);

Also you should want to do it inside a try block in order to announce that it succeeded only if it really did:此外,您应该希望在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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM