Safe File Operations
Definition
Program.cs
12345678910111213141516171819202122232425262728using System; using System.IO; namespace ConsoleApp { public class Program { public static void Main(string[] args) { string path = "data.txt"; try { string content = File.ReadAllText(path); Console.WriteLine("File content:"); Console.WriteLine(content); } catch (FileNotFoundException) { Console.WriteLine("Error: The file was not found."); } catch (IOException ex) { Console.WriteLine($"An I/O error occurred: {ex.Message}"); } } } }
WritingExample.cs
123456789101112131415161718192021222324using System; using System.IO; namespace ConsoleApp { public class WritingExample { public void WriteToFile(string path, string text) { try { using (StreamWriter writer = new StreamWriter(path)) { writer.WriteLine(text); } } catch (IOException ex) { Console.WriteLine($"Could not write to file: {ex.Message}"); } } } }
Alt var klart?
Takk for tilbakemeldingene dine!
Seksjon 4. Kapittel 1
Spør AI
Spør AI
Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår
Suggested prompts:
Can you show me an example of how to handle these exceptions in C#?
What are some other common file-related exceptions in C#?
How do I check if a file exists before trying to read or write?
Fantastisk!
Completion rate forbedret til 4.17
Safe File Operations
Sveip for å vise menyen
Definition
Program.cs
12345678910111213141516171819202122232425262728using System; using System.IO; namespace ConsoleApp { public class Program { public static void Main(string[] args) { string path = "data.txt"; try { string content = File.ReadAllText(path); Console.WriteLine("File content:"); Console.WriteLine(content); } catch (FileNotFoundException) { Console.WriteLine("Error: The file was not found."); } catch (IOException ex) { Console.WriteLine($"An I/O error occurred: {ex.Message}"); } } } }
WritingExample.cs
123456789101112131415161718192021222324using System; using System.IO; namespace ConsoleApp { public class WritingExample { public void WriteToFile(string path, string text) { try { using (StreamWriter writer = new StreamWriter(path)) { writer.WriteLine(text); } } catch (IOException ex) { Console.WriteLine($"Could not write to file: {ex.Message}"); } } } }
Alt var klart?
Takk for tilbakemeldingene dine!
Seksjon 4. Kapittel 1