Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
.net 创建临时文件夹_.net_Io - Fatal编程技术网

.net 创建临时文件夹

.net 创建临时文件夹,.net,io,.net,Io,我正在开发一个需要为应用程序创建多个临时文件夹的程序。用户将看不到这些。该应用程序是用VB.net编写的。我可以想出一些方法,比如递增文件夹名或随机编号的文件夹名,但我想知道,其他人是如何解决这个问题的?只要文件夹名不需要有意义,为它们使用GUID如何?您可以为临时文件夹名生成GUID。您可以使用创建临时文件,然后删除此文件并将其重新创建为目录 注意:链接无效,请从以下位置复制/粘贴:您必须使用System.IO.Path.GetTempFileName() 在磁盘上创建一个唯一命名的零字节临时

我正在开发一个需要为应用程序创建多个临时文件夹的程序。用户将看不到这些。该应用程序是用VB.net编写的。我可以想出一些方法,比如递增文件夹名或随机编号的文件夹名,但我想知道,其他人是如何解决这个问题的?

只要文件夹名不需要有意义,为它们使用GUID如何?

您可以为临时文件夹名生成GUID。

您可以使用创建临时文件,然后删除此文件并将其重新创建为目录


注意:链接无效,请从以下位置复制/粘贴:

您必须使用
System.IO.Path.GetTempFileName()

在磁盘上创建一个唯一命名的零字节临时文件,并返回该文件的完整路径

您可以使用
System.IO.Path.GetDirectoryName(System.IO.Path.GetTempFileName())
仅获取临时文件夹信息,并在其中创建文件夹

它们是在Windows临时文件夹中创建的,这是一个最佳实践:

< P>…………< /P>
using System.IO;

string path = Path.GetTempPath() + Path.GetRandomFileName();
while (Directory.Exists(path))
 path = Path.GetTempPath() + Path.GetRandomFileName();

Directory.CreateDirectory(path);

来自@adam wright和pix0r的组合答案将最适合IMHO:


using System.IO;

string path = Path.GetTempPath() + Path.GetRandomFileName();

while (Directory.Exists(path)) 
  path = Path.GetTempPath() + Path.GetRandomFileName();

File.Delete(path);
Directory.CreateDirectory(path);

使用System.IO.Path.GetTempFileName的优点是它将是用户本地(即非漫游)路径中的文件。出于权限和安全原因,这正是您需要它的地方。

更新:添加了文件。根据注释检查是否存在(2012-6-19)

下面是我在VB.NET中使用的内容。基本上与演示的相同,只是我通常不想立即创建文件夹

使用它的优点是它不会创建文件,因此,如果您将名称用于文件以外的其他内容,则不必进行清理。比如用它来命名文件夹

Private Function GetTempFolder() As String
    Dim folder As String = Path.Combine(Path.GetTempPath, Path.GetRandomFileName)
    Do While Directory.Exists(folder) or File.Exists(folder)
        folder = Path.Combine(Path.GetTempPath, Path.GetRandomFileName)
    Loop

    Return folder
End Function
随机文件名示例:

C:\Documents and Settings\username\Local Settings\Temp\u3z5e0co.tvq


下面是一个使用Guid获取临时文件夹名称的变体

Private Function GetTempFolderGuid() As String
    Dim folder As String = Path.Combine(Path.GetTempPath, Guid.NewGuid.ToString)
    Do While Directory.Exists(folder) or File.Exists(folder)
        folder = Path.Combine(Path.GetTempPath, Guid.NewGuid.ToString)
    Loop

    Return folder
End Function
guid示例:

C:\Documents and Settings\username\Local Settings\Temp\2dbc6db7-2d45-4b75-b27f-0bd492c60496仅澄清一下:

System.IO.Path.GetTempPath()
只返回临时文件夹的文件夹路径

System.IO.Path.GetTempFileName()
返回完全限定的文件名(包括路径),因此:


是冗余的。

在以下情况下可能存在争用条件:

  • 使用
    GetTempFileName()
    创建临时文件,删除它,并使用相同的名称创建文件夹,或
  • 使用
    GetRandomFileName()
    Guid.NewGuid.ToString
    命名文件夹,然后创建文件夹
在删除发生后,使用
GetTempFileName()
,另一个应用程序可以成功创建具有相同名称的临时文件。
CreateDirectory()
将失败

类似地,在调用
GetRandomFileName()
和创建目录之间,另一个进程可能会创建具有相同名称的文件或目录,再次导致
CreateDirectory()
失败

对于大多数应用程序,临时目录由于竞争条件而失败是可以的。毕竟这是非常罕见的。对他们来说,这些种族往往被忽视

在unixshell脚本世界中,以安全无竞争的方式创建临时文件和目录是一件大事。许多机器都有多个(敌对的)用户——比如说共享web主机——许多脚本和应用程序需要在shared/tmp目录中安全地创建临时文件和目录。有关如何从shell脚本安全创建临时目录的讨论,请参阅。

作为@JonathanWright,解决方案存在竞争条件:

  • 使用
    GetTempFileName()
    创建一个临时文件,删除它,然后创建一个同名文件夹
  • 使用
    GetRandomFileName()
    Guid.NewGuid.ToString
    创建随机文件夹名称,检查它是否存在,如果不存在,则创建它
但是,通过利用(TxF)API,可以原子地创建唯一的临时目录

TxF有一个可以通过平台调用调用的函数。为此,我适应了调用
createFileTransact()

//使用System.ComponentModel;
//使用System.Runtime.InteropServices;
//使用系统事务;
[ComImport]
[Guid(“79427a2b-f895-40e0-be79-b57dc82ed231”)]
[接口类型(ComInterfaceType.InterfaceSiunknown)]
公共接口IKernelTransaction
{
void GetHandle(out IntPtr pHandle);
}
//2.2 Win32错误代码
public const int ERROR\u PATH\u NOT\u FOUND=0x3;
public const int ERROR_已存在=0xb7;
事务中的公共常量int错误\u EFS\u不允许\u=0x1aaf;
[DllImport(“kernel32.dll”,SetLastError=true,CharSet=CharSet.Auto)]
public static extern bool createdirectorytransactioned(字符串lptemplateddirectory、字符串lpNewDirectory、IntPtr lpSecurityAttributes、IntPtr hTransaction);
/// 
///在名为的目录中创建唯一命名的目录,并返回其路径。
/// 
///将在其中创建临时目录的目录的路径。
///中新创建的临时目录的路径。
公共静态字符串GetTempDirectoryName(字符串tempPath)
{
字符串路径;
使用(TransactionScope TransactionScope=new TransactionScope())
{
IKernelTransaction kernelTransaction=(IKernelTransaction)TransactionInterop.GetDtcTransaction(Transaction.Current);
IntPtr-hTransaction;
GetHandle(out-hTransaction);
而(!CreateDirectoryTransactive(null,retPath=Path.Combine(tempPath,Path.GetRandomFileName()),IntPtr.Zero,hTransaction))
{
int lastWin32Error=Marshal.GetLastWin32Error();
开关(lastWin32Error)
{
案例错误\u已\u存在:
打破
违约:
抛出新的Win32Exception(lastWin32Error);
System.IO.Path.Combine(System.IO.Path.GetTempPath(), System.IO.Path.GetTempFileName())
// using System.ComponentModel;
// using System.Runtime.InteropServices;
// using System.Transactions;

[ComImport]
[Guid("79427a2b-f895-40e0-be79-b57dc82ed231")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IKernelTransaction
{
    void GetHandle(out IntPtr pHandle);
}

// 2.2 Win32 Error Codes <http://msdn.microsoft.com/en-us/library/cc231199.aspx>
public const int ERROR_PATH_NOT_FOUND = 0x3;
public const int ERROR_ALREADY_EXISTS = 0xb7;
public const int ERROR_EFS_NOT_ALLOWED_IN_TRANSACTION = 0x1aaf;

[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
public static extern bool CreateDirectoryTransacted(string lpTemplateDirectory, string lpNewDirectory, IntPtr lpSecurityAttributes, IntPtr hTransaction);

/// <summary>
/// Creates a uniquely-named directory in the directory named by <paramref name="tempPath"/> and returns the path to it.
/// </summary>
/// <param name="tempPath">Path of a directory in which the temporary directory will be created.</param>
/// <returns>The path of the newly-created temporary directory within <paramref name="tempPath"/>.</returns>
public static string GetTempDirectoryName(string tempPath)
{
    string retPath;

    using (TransactionScope transactionScope = new TransactionScope())
    {
        IKernelTransaction kernelTransaction = (IKernelTransaction)TransactionInterop.GetDtcTransaction(Transaction.Current);
        IntPtr hTransaction;
        kernelTransaction.GetHandle(out hTransaction);

        while (!CreateDirectoryTransacted(null, retPath = Path.Combine(tempPath, Path.GetRandomFileName()), IntPtr.Zero, hTransaction))
        {
            int lastWin32Error = Marshal.GetLastWin32Error();
            switch (lastWin32Error)
            {
                case ERROR_ALREADY_EXISTS:
                    break;
                default:
                    throw new Win32Exception(lastWin32Error);
            }
        }

        transactionScope.Complete();
    }
    return retPath;
}

/// <summary>
/// Equivalent to <c>GetTempDirectoryName(Path.GetTempPath())</c>.
/// </summary>
/// <seealso cref="GetTempDirectoryName(string)"/>
public static string GetTempDirectoryName()
{
    return GetTempDirectoryName(Path.GetTempPath());
}
Dim NewFolder = System.IO.Directory.CreateDirectory(IO.Path.Combine(IO.Path.GetTempPath, Guid.NewGuid.ToString))
Private Function GetTempFolder() As String
    Dim folder As String
    Dim succes as Boolean = false
    Do While not succes
        folder = Path.Combine(Path.GetTempPath, Path.GetRandomFileName)
        success = c_api_create_directory(folder)
    Loop
    Return folder
End Function