RAGECOOP-V/Client/DownloadManager.cs

65 lines
1.9 KiB
C#
Raw Normal View History

2022-04-02 18:11:30 +02:00
using System.IO;
2022-04-02 16:40:24 +02:00
namespace CoopClient
{
internal class DownloadManager
{
2022-04-02 18:11:30 +02:00
public byte FileID { get; set; }
2022-04-02 16:40:24 +02:00
public Packets.DataFileType FileType { get; set; }
public string FileName { get; set; }
2022-04-02 18:11:30 +02:00
public long FileLength { get; set; }
2022-04-02 16:40:24 +02:00
2022-04-02 18:11:30 +02:00
private readonly FileStream _stream;
public DownloadManager()
2022-04-02 16:40:24 +02:00
{
2022-04-02 18:11:30 +02:00
string downloadFolder = $"scripts\\{Main.MainSettings.LastServerAddress.Replace(":", ".")}";
if (!Directory.Exists(downloadFolder))
{
Directory.CreateDirectory(downloadFolder);
if (FileAlreadyExists(downloadFolder))
{
// Send the server we are already done
Main.MainNetworking.SendDownloadFinish(FileID);
return;
2022-04-02 18:11:30 +02:00
}
}
_stream = new FileStream(downloadFolder + "\\" + FileName, FileMode.CreateNew);
2022-04-02 16:40:24 +02:00
}
2022-04-02 18:11:30 +02:00
/// <summary>
/// Check if the file already exists and if the size correct otherwise delete this file
/// </summary>
/// <param name="folder"></param>
private bool FileAlreadyExists(string folder)
2022-04-02 16:40:24 +02:00
{
2022-04-02 18:11:30 +02:00
string filePath = $"{folder}\\{FileName}";
if (File.Exists(filePath))
{
if (new FileInfo(filePath).Length == FileLength)
{
return true;
}
else
{
// Delete the file because the length is wrong (maybe the file was updated)
File.Delete(filePath);
}
}
2022-04-02 16:40:24 +02:00
2022-04-02 18:11:30 +02:00
return false;
}
public void DownloadPart(byte[] data)
{
_stream.Write(data, 0, data.Length);
if (data.Length >= FileLength)
{
_stream.Close();
_stream.Dispose();
}
2022-04-02 16:40:24 +02:00
}
}
}