FileWork examples were added

This commit is contained in:
ear
2024-09-06 18:13:21 +05:00
parent 2268557672
commit 408e9f6999
13 changed files with 811 additions and 0 deletions

View File

@@ -0,0 +1,49 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace DataAccess.FileDialogs
{
public class FileDialogOpener
{
public void OpenFileAndRead()
{
// Create an instance of OpenFileDialog
using (OpenFileDialog openFileDialog = new OpenFileDialog())
{
// Set filter options and filter index
openFileDialog.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*";
openFileDialog.FilterIndex = 1;
openFileDialog.Multiselect = false; // Set to true if you want to allow multiple file selection
openFileDialog.Title = "Select a File";
// Show the dialog and get result
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
// Get the path of the selected file
string selectedFilePath = openFileDialog.FileName;
// Read the content of the file
try
{
string fileContent = File.ReadAllText(selectedFilePath);
Console.WriteLine($"File Content of '{selectedFilePath}':");
Console.WriteLine(fileContent);
}
catch (IOException ex)
{
Console.WriteLine($"An error occurred while reading the file: {ex.Message}");
}
}
else
{
Console.WriteLine("File selection was cancelled.");
}
}
}
}
}

View File

@@ -0,0 +1,93 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DataAccess.FileDialogs
{
using System;
using System.IO;
using System.Threading.Tasks;
public class FileRepository : IFileRepository
{
private readonly string _storageDirectory;
public FileRepository(string storageDirectory)
{
_storageDirectory = storageDirectory;
// Ensure the storage directory exists
if (!Directory.Exists(_storageDirectory))
{
Directory.CreateDirectory(_storageDirectory);
}
}
// Save a file to the repository
public async Task SaveFileAsync(Stream fileStream, string fileName)
{
string filePath = Path.Combine(_storageDirectory, fileName);
// Ensure the file does not already exist
if (File.Exists(filePath))
{
throw new InvalidOperationException("File already exists.");
}
using (var file = new FileStream(filePath, FileMode.Create, FileAccess.Write))
{
await fileStream.CopyToAsync(file);
}
}
// Retrieve a file from the repository
public async Task<Stream> GetFileAsync(string fileName)
{
string filePath = Path.Combine(_storageDirectory, fileName);
// Ensure the file exists
if (!File.Exists(filePath))
{
throw new FileNotFoundException("File not found.");
}
var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
return await Task.FromResult(fileStream);
}
// Update an existing file in the repository
public async Task UpdateFileAsync(Stream fileStream, string fileName)
{
string filePath = Path.Combine(_storageDirectory, fileName);
// Ensure the file exists
if (!File.Exists(filePath))
{
throw new FileNotFoundException("File not found.");
}
using (var file = new FileStream(filePath, FileMode.Truncate, FileAccess.Write))
{
await fileStream.CopyToAsync(file);
}
}
// Delete a file from the repository
public async Task DeleteFileAsync(string fileName)
{
string filePath = Path.Combine(_storageDirectory, fileName);
// Ensure the file exists
if (!File.Exists(filePath))
{
throw new FileNotFoundException("File not found.");
}
File.Delete(filePath);
await Task.CompletedTask;
}
}
}

View File

@@ -0,0 +1,139 @@
using DataAccess.FileDialogs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace DataAccess.FileDialogs
{
internal class FileStorage
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Windows.Forms;
public class FileStorageManager
{
// Dictionary to store files with unique IDs as keys
private readonly Dictionary<Guid, OpenedFile> _openedFiles = new Dictionary<Guid, OpenedFile>();
// Method to open a file and add it to the storage
public Guid OpenFile()
{
using (OpenFileDialog openFileDialog = new OpenFileDialog())
{
openFileDialog.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*";
openFileDialog.Multiselect = true; // Allow multiple file selection
openFileDialog.Title = "Select Files";
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
foreach (var filePath in openFileDialog.FileNames)
{
var fileId = Guid.NewGuid();
var openedFile = new OpenedFile(fileId, filePath);
// Add to storage
_openedFiles[fileId] = openedFile;
Console.WriteLine($"File '{openedFile.FilePath}' opened with ID: {fileId}");
}
}
}
return Guid.Empty;
}
// Method to get an opened file by ID
public OpenedFile GetFile(Guid fileId)
{
if (_openedFiles.TryGetValue(fileId, out var openedFile))
{
return openedFile;
}
throw new KeyNotFoundException("File not found.");
}
// Method to close a file by ID
public void CloseFile(Guid fileId)
{
if (_openedFiles.ContainsKey(fileId))
{
_openedFiles.Remove(fileId);
Console.WriteLine($"File with ID: {fileId} has been closed.");
}
else
{
throw new KeyNotFoundException("File not found.");
}
}
// Method to read content of an opened file by ID
public string ReadFileContent(Guid fileId)
{
var openedFile = GetFile(fileId);
return File.ReadAllText(openedFile.FilePath);
}
// Method to list all opened files
public void ListOpenedFiles()
{
foreach (var file in _openedFiles.Values)
{
Console.WriteLine($"File ID: {file.Id}, Path: {file.FilePath}");
}
}
}
// Class representing an opened file
public class OpenedFile
{
public Guid Id { get; }
public string FilePath { get; }
public OpenedFile(Guid id, string filePath)
{
Id = id;
FilePath = filePath;
}
}
}
class Program
{
[STAThread] // Required for OpenFileDialog
static void Main()
{
var fileStorageManager = new FileStorageManager();
// Open files and add them to the storage
fileStorageManager.OpenFile();
// List all opened files
Console.WriteLine("\nOpened Files:");
fileStorageManager.ListOpenedFiles();
// Example: Read content of the first opened file (if any)
var openedFiles = new List<Guid>(fileStorageManager._openedFiles.Keys);
if (openedFiles.Count > 0)
{
var firstFileId = openedFiles[0];
Console.WriteLine($"\nReading content of the first opened file (ID: {firstFileId}):");
string content = fileStorageManager.ReadFileContent(firstFileId);
Console.WriteLine(content);
}
// Close all files
foreach (var fileId in openedFiles)
{
fileStorageManager.CloseFile(fileId);
}
}
}
}

View File

@@ -0,0 +1,14 @@
using System.IO;
using System.Threading.Tasks;
namespace DataAccess.FileDialogs
{
public interface IFileRepository
{
Task SaveFileAsync(Stream fileStream, string fileName);
Task<Stream> GetFileAsync(string fileName);
Task DeleteFileAsync(string fileName);
Task UpdateFileAsync(Stream fileStream, string fileName);
}
}

View File

@@ -0,0 +1,62 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DataAccess.FileDialogs
{
using System;
using System.IO;
using System.Text;
using System.Threading.Tasks;
class ProgramExample
{
static async Task Main(string[] args)
{
string storagePath = Path.Combine(Environment.CurrentDirectory, "UserFiles");
IFileRepository fileRepository = new FileRepository(storagePath);
// Save a file
string fileName = "example.txt";
using (var fileStream = new MemoryStream(Encoding.UTF8.GetBytes("Hello, World!")))
{
await fileRepository.SaveFileAsync(fileStream, fileName);
Console.WriteLine($"File '{fileName}' saved.");
}
// Retrieve a file
using (Stream retrievedFile = await fileRepository.GetFileAsync(fileName))
{
using (var reader = new StreamReader(retrievedFile))
{
string content = await reader.ReadToEndAsync();
Console.WriteLine($"Retrieved file content: {content}");
}
}
// Update a file
using (var updateStream = new MemoryStream(Encoding.UTF8.GetBytes("Updated content!")))
{
await fileRepository.UpdateFileAsync(updateStream, fileName);
Console.WriteLine($"File '{fileName}' updated.");
}
// Retrieve updated file
using (Stream updatedFile = await fileRepository.GetFileAsync(fileName))
{
using (var reader = new StreamReader(updatedFile))
{
string updatedContent = await reader.ReadToEndAsync();
Console.WriteLine($"Updated file content: {updatedContent}");
}
}
// Delete a file
await fileRepository.DeleteFileAsync(fileName);
Console.WriteLine($"File '{fileName}' deleted.");
}
}
}