Ana içeriğe atla

Read, write and delete files in windows

Sooner or later you'll need to access files from the Window's file system. You'll need to check if a file exists, delete it, move it , you'll need to read and write to it and upload data from it to an iSeries table etc.

To illustrate how easy this is, I've included a full C# project.

This program cleans up a desktop. It moves unwanted items automatically to a 'clean up' folder automatically. Items you don't want to remove are maintained in a text file manually. This file is in 'CleanUp' on your desktop after you run it the first time.
Set it up to run in 'scheduled tasks' to run daily. My desktop gets absolutely splattered with downloads, images, files etc. etc. Now it gets cleaned automatically and the stuff I want to keep is always there. Files are moved but not folders.

The app demonstrates two things.

  1. How to access the windows file system
  2. How to write a RPG-like app in C#. i.e. in a procedural way There is a 'main', an init etc. There are no class objects created, everything runs from the class. Methods are just like subroutines. Variables are defined that are needed throughout the application as public at the top of the class. (If you define a variable in a method - it is only available within that method.)
using System;
using System.Collections.Generic;

using System.Text;
using System.IO;

using System.Security.Principal;


//Lists each object on the desktop
//Checks if the object is in the list.
//If not, moves it to cleanup.

namespace ClearDesktop
{
class Program
{

// Declare class level variables that are accessible from all methods
public static string cleanUpFolder = @"Cleanup\";
public static string desktopPathAllUsers = @"C:\Documents and Settings\All Users\Desktop\";
public static string desktopPath = "";
public static string cleanUpPath = "";
public static string cleanUpFile = "";
public static string allowedOnDesktop = "";



// Main Routine
static void Main(string[] args)
{
initializationRoutine(); // Set paths needed

RemoveFilesFromDesktop(desktopPath); // remove unwanted files
RemoveFilesFromDesktop(desktopPathAllUsers); // some file paths are in 'all users'
// Console.ReadLine();
}




public static void RemoveFilesFromDesktop(string dir)
{
// First create directory object from the desktop path
DirectoryInfo mainDir = new DirectoryInfo(dir);


// This single line fills an array called 'items' of everything on the desktop

// The items in the array are not strings but FileSystemInfo objects.


// What's cool here is each item has a ton of methods and properties


// available directly from it.



            FileSystemInfo[] items = mainDir.GetFileSystemInfos();



// Now go through each item in the array and check if it is allowed
foreach (FileSystemInfo item in items)
{
// Check if the file on the desktop is in the 'allowed' file
bool allowedyn = allowedOnDesktop.Contains(item.Name.ToString());

if (item is FileInfo && !allowedyn)
{
// If it is to be moved any existing same name file has to be deleted
String alreadyExists = cleanUpPath + item;

if (File.Exists(alreadyExists))
{
try
{
// Delete the file with the same name
File.Delete(alreadyExists);
}
catch (Exception)
{


}

}

// Move the file on the desktop to the clean up folder
((FileInfo)item).MoveTo(cleanUpPath + item);

}

}
}




// Get a list of all the files allowed on the desktop
public static string WhatsAllowedOnTheDesktop(string logFileName)
{

string contents = "";

using (FileStream fileStream = new FileStream(logFileName,
FileMode.Open,
FileAccess.Read,
FileShare.None))
{
using (StreamReader Reader = new StreamReader(fileStream))
{
contents = Reader.ReadToEnd(); // Reads the entire file in one statement
Reader.Close();
fileStream.Close();
}


}
return contents;
}

// Write to the 'Allowed files' directory those files you don't want to move
public static void WriteToLog(string logFileName, string data)
{
using (FileStream fileStream = new FileStream(logFileName,
FileMode.Append,
FileAccess.Write,
FileShare.None))
{
using (StreamWriter streamWriter = new StreamWriter(fileStream))
{
streamWriter.WriteLine(data);
}
}
}

// Do basic setup - path names etc.
public static void initializationRoutine() {
string username = getUserName();

desktopPath = @"C:\Documents and Settings\" + username + @"\Desktop\";
cleanUpPath = desktopPath + cleanUpFolder;
cleanUpFile = cleanUpPath + @"CleanUpFile.txt";

// If the cleanup directory does not exist, create it
if (!Directory.Exists(cleanUpPath))
{
Directory.CreateDirectory(cleanUpPath);
}

// Create the log file of items you want to keep on the desktop

if (!File.Exists(cleanUpFile))
{
File.Create(cleanUpFile);
}

allowedOnDesktop = WhatsAllowedOnTheDesktop(cleanUpFile);
}

// Get the log on name of the user who started the app in order
// to know the path of their desktop
public static string getUserName()
{
WindowsIdentity ident = WindowsIdentity.GetCurrent();

string userid = ident.Name;
string username = "";
int pos = userid.IndexOf("\\");
if (pos > -1)
{

username = userid.Substring(pos + 1);
}
else
{
username = userid;
}


return username;

}

}



}

Yorumlar

Bu blogdaki popüler yayınlar

SharePoint 2010 - Content Query for Blog Posts

I hope this post will help many of you feel comfortable with using the Content Query Web Part. In this post I will walk you through the process of creating a content query web part and configuring it to show custom field types. I will also give details on how to use XSLT to stylize and format the data being pulled. I will be using the following scenario as an example. Say that you had a site collection with a top level publishing site. This publishing site would display a the most recent blog posts from all blog sites within its own site collection. To solve this problem we will use a Content Query Web Part and a customized ItemStyle.xsl using XSLT. Please note that the “SharePoint Server Publishing Infrastructure” needs to be enabled at the site collection to display the content query web part. Step 1: Add a Content Query Web Part to Page Navigate to the site that you want the blog posts to show up and click on edit page. Under Editing Tools in the Ribb

.Net 3.5 SP1 – Full Install Packages (Tam Kurulum)

.Net Framework 3.5 SP1 ‘i bilgisayarınıza kurmak istediğinizde normal şartlar altında Microsoft ‘un sitesinde 2.7 mb ‘lik bir dosya indirir ve kurulum işlemlerinizi bu dosya üzerinden yaparsınız. Ancak bu indirmiş oluğunuz dosya yaklaşık 220 mb ‘lik veriyi internetten indirerek kurulum yapmaktadır. İnternet çıkışına izin verilmeyen kurumlar ve kuruluşlar için bu durum bir sıkıntı oluşturmaktadır. Bu sebepten ötürü aşağıdaki link yardımı ile tam yükleme paketini indirdikten sonra hiç internet ihtiyacınız olmadan .Net 3.5 SP1 ‘i kurabilmeniz mümkün olacaktır. Link

Olasılıksız - Kitap Yorum

Olasılıksız hayatımda okuduğum en iyi kitaptı. Tek çırpıda hiç sıkılmadan, eğlenerek okudum bu kitabı, tavsiyem sizinde okumanız. Kitabın kapağı ve içeriği ile ilgili kısa bilgi aşağıdadır. Olasılık, tahmin, düşünceler, nöbetler, karışıklıklar, ileriyi görebilme zannı, dejavu ve tabii ki olasılıksız şeyler. Bu kelimelerle içli dışlı olabileceğiniz, bütün bu kelimelerin yaşamdaki yerini kavrayabileceğiniz müthiş bir uyarlama. Adam Fawer' ın ortaya çıkardığı bu uyarlama romanın müthiş bir çalışmanın ve araştırmanın sonucu ortaya çıktığının kitabın başından sonuna kadar farkındasınız. Bu uyarlamasını, derin araştırmalarıyla birleştirip romanı tekdüzelikten çıkarıp müthiş bir yere koyduğu için de Fawer' a müteşekkir oluveriyorsunuz. Sıkıcı diye nitelendirebileceğiniz teorik bilgileri bile bir çırpıda okuyuveriyorsunuz. Teorik bilgiler dahi olaylarla sonuna kadar bağlantılı aktarılmış. Tekdüzelikten çıkmış bir roman; olasılıksız. Her an olayın kurgusunun değişmesi olasılık dahilind