简体   繁体   中英

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. 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.

Now I have created a folder named "test" inside the current directory using the following code:

            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. 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:

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 :

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
{
    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);...}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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